KVO實(shí)現(xiàn)自定義文件復(fù)制進(jìn)度效果
本文實(shí)例為大家分享了KVO實(shí)現(xiàn)自定義文件復(fù)制進(jìn)度展示的具體代碼,供大家參考,具體內(nèi)容如下
一、創(chuàng)建文件
說(shuō)明:自定義文件類(lèi),通過(guò)NSFileManager 以及NSFileHandle 實(shí)現(xiàn)文件的創(chuàng)建和copy,為了控制內(nèi)存的并發(fā)使用,通過(guò)控制每次賦值的固定長(zhǎng)度來(lái)分多次復(fù)制:
NSString * path=NSHomeDirectory();
path =[path stringByAppendingPathComponent:@"deskTop/Boby.m"];
NSString * target=NSHomeDirectory();
target =[target stringByAppendingPathComponent:@"deskTop/target.m"];
NSFileManager * manager=[NSFileManager defaultManager];
//校驗(yàn)并且創(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];
二、設(shè)置觀察者
說(shuō)明:自定義使用者,通過(guò)設(shè)置觀察者來(lái)動(dòng)態(tài)觀察當(dāng)前文件copy的進(jìn)度并展示到控制臺(tái)或者輸出到UI,并提供方法接口,啟動(dòng)文件拷貝。
- (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);
//一定不能忘了銷(xiāo)毀當(dāng)前的觀察者
if(result==1){
[self.file removeObserver:self forKeyPath:@"nowSize"];
}
}
- (void) begin{
[self.file startCopy];
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Flutter?ScrollController滾動(dòng)監(jiān)聽(tīng)及控制示例詳解
這篇文章主要為大家介紹了Flutter?ScrollController滾動(dòng)監(jiān)聽(tīng)及控制示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
iOS 對(duì)當(dāng)前webView進(jìn)行截屏的方法
下面小編就為大家?guī)?lái)一篇iOS 對(duì)當(dāng)前webView進(jìn)行截屏的方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-04-04
iOS統(tǒng)計(jì)項(xiàng)目的代碼總行數(shù)
最近一個(gè)項(xiàng)目有段時(shí)間了,不知道怎樣可以統(tǒng)計(jì)出寫(xiě)了多少行代碼,如何處理這個(gè)問(wèn)題呢,下面我們來(lái)探討下。2015-06-06

