小编给大家分享一下KVO如何实现自定义文件复制进度效果,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
一、创建文件
说明:自定义文件类,通过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];
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];
二、设置观察者
说明:自定义使用者,通过设置观察者来动态观察当前文件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如何实现自定义文件复制进度效果”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。