KVO实现自定义文件复制进度展示

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

一、创建文件

说明:自定义文件类,通过NSFileManager 以及NSFileHandle 实现文件的创建和copy,为了控制内存的并发使用,通过控制每次赋值的固定长度来分多次复制:

NSString * path=NSHomeDirectory();

path=[path stringByAppendingPathComponent:@"deskTop/Boby.m"];

NSString* target=NSHomeDirectory();

target=[target stringByAppendingPathComponent:@"deskTop/target.m"];

NSFileManager* manager=[NSFileManager defaultManager];//校验并且创建文件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];inttotal=(int)[dic[@"NSFileSize"] integerValue];

self.totalSize=total;intper=50;intcount=total%per==0?total/per:total/per+1;for(inti=0;i<count;i++){

[handle seekToFileOffset:self.nowSize];

NSData*data=[handle readDataOfLength:per];inttem=per*(i+1);if(tem>total){

tem=total;

}

self.nowSize=tem;

[handletTarget seekToEndOfFile];

[handletTarget writeData:data];

[NSThread sleepForTimeInterval:0.2];

}

[handle closeFile];

[handletTarget closeFile];

二、设置观察者

说明:自定义使用者,通过设置观察者来动态观察当前文件copy的进度并展示到控制台或者输出到UI,并提供方法接口,启动文件拷贝。

- (id) initWithFile:(FileMake *)files{

self=[super init];if(self){

self.file=files;

[self.file addObserver:self forKeyPath:@"nowSize"options:NSKeyValueObservingOptionNew context:nil];

}returnself;

}-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)objectchange:(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];

}

作者:杰瑞教育

出处:http://www.cnblogs.com/jerehedu/

本文版权归烟台杰瑞教育科技有限公司和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航