小編給大家分享一下KVO如何實現(xiàn)自定義文件復制進度效果,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

一、創(chuàng)建文件
說明:自定義文件類,通過NSFileManager 以及NSFileHandle 實現(xiàn)文件的創(chuàng)建和copy,為了控制內存的并發(fā)使用,通過控制每次賦值的固定長度來分多次復制:
NSString * path=NSHomeDirectory();
path =[path stringByAppendingPathComponent:@"deskTop/Boby.m"];
NSString * target=NSHomeDirectory();
target =[target stringByAppendingPathComponent:@"deskTop/target.m"];
NSFileManager * manager=[NSFileManager defaultManager];
//校驗并且創(chuàng)建文件
if(![manager fileExistsAtPath:path]){
[manager createFileAtPath:path contents:nil attributes:nil];
}
if(![manager fileExistsAtPath:target]){
[manager createFileAtPath:target contents:nil attributes:nil];
}
NSDictionary * dic=[manager attributesOfItemAtPath:path error:nil];
NSFileHandle * handle=[NSFileHandle fileHandleForReadingAtPath:path];
NSFileHandle * handletTarget=[NSFileHandle fileHandleForWritingAtPath:target];
int total=(int)[dic[@"NSFileSize"] integerValue];
self.totalSize=total;
int per=50;
int count=total%per==0?total/per:total/per+1;
for(int i=0;i<count;i++){
[handle seekToFileOffset:self.nowSize];
NSData *data= [handle readDataOfLength:per];
int tem=per*(i+1);
if(tem>total){
tem=total;
}
self.nowSize=tem;
[handletTarget seekToEndOfFile];
[handletTarget writeData:data];
[NSThread sleepForTimeInterval:0.2];
}
[handle closeFile];
[handletTarget closeFile];二、設置觀察者
說明:自定義使用者,通過設置觀察者來動態(tài)觀察當前文件copy的進度并展示到控制臺或者輸出到UI,并提供方法接口,啟動文件拷貝。
- (id) initWithFile:(FileMake *)files{
self=[super init];
if(self){
self.file= files;
[self.file addObserver:self forKeyPath:@"nowSize" options:NSKeyValueObservingOptionNew context:nil];
}
return self;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
CGFloat all=self.file.totalSize;
CGFloat now=[[change objectForKey:@"new"] floatValue];
CGFloat result=now/all;
NSLog(@"%.2f",result);
//一定不能忘了銷毀當前的觀察者
if(result==1){
[self.file removeObserver:self forKeyPath:@"nowSize"];
}
}
- (void) begin{
[self.file startCopy];
}看完了這篇文章,相信你對“KVO如何實現(xiàn)自定義文件復制進度效果”有了一定的了解,如果想了解更多相關知識,歡迎關注創(chuàng)新互聯(lián)網(wǎng)站建設公司行業(yè)資訊頻道,感謝各位的閱讀!
另外有需要云服務器可以了解下創(chuàng)新互聯(lián)建站chinadenli.net,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
本文題目:KVO如何實現(xiàn)自定義文件復制進度效果-創(chuàng)新互聯(lián)
URL地址:http://chinadenli.net/article18/dghgdp.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供用戶體驗、做網(wǎng)站、網(wǎng)站排名、網(wǎng)站設計、網(wǎng)頁設計公司、靜態(tài)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內容