KVO实现自定义文件复制进度效果
本文实例为大家分享了KVO实现自定义文件复制进度展示的具体代码,供大家参考,具体内容如下
一、创建文件
说明:自定义文件类,通过NSFileManager以及NSFileHandle实现文件的创建和copy,为了控制内存的并发使用,通过控制每次赋值的固定长度来分多次复制:
NSString*path=NSHomeDirectory();
path=[pathstringByAppendingPathComponent:@"deskTop/Boby.m"];
NSString*target=NSHomeDirectory();
target=[targetstringByAppendingPathComponent:@"deskTop/target.m"];
NSFileManager*manager=[NSFileManagerdefaultManager];
//校验并且创建文件
if(![managerfileExistsAtPath:path]){
[managercreateFileAtPath:pathcontents:nilattributes:nil];
}
if(![managerfileExistsAtPath:target]){
[managercreateFileAtPath:targetcontents:nilattributes:nil];
}
NSDictionary*dic=[managerattributesOfItemAtPath:patherror:nil];
NSFileHandle*handle=[NSFileHandlefileHandleForReadingAtPath:path];
NSFileHandle*handletTarget=[NSFileHandlefileHandleForWritingAtPath:target];
inttotal=(int)[dic[@"NSFileSize"]integerValue];
self.totalSize=total;
intper=50;
intcount=total%per==0?total/per:total/per+1;
for(inti=0;itotal){
tem=total;
}
self.nowSize=tem;
[handletTargetseekToEndOfFile];
[handletTargetwriteData:data];
[NSThreadsleepForTimeInterval:0.2];
}
[handlecloseFile];
[handletTargetcloseFile];
二、设置观察者
说明:自定义使用者,通过设置观察者来动态观察当前文件copy的进度并展示到控制台或者输出到UI,并提供方法接口,启动文件拷贝。
-(id)initWithFile:(FileMake*)files{
self=[superinit];
if(self){
self.file=files;
[self.fileaddObserver:selfforKeyPath:@"nowSize"options:NSKeyValueObservingOptionNewcontext:nil];
}
returnself;
}
-(void)observeValueForKeyPath:(NSString*)keyPathofObject:(id)objectchange:(NSDictionary*)changecontext:(void*)context{
CGFloatall=self.file.totalSize;
CGFloatnow=[[changeobjectForKey:@"new"]floatValue];
CGFloatresult=now/all;
NSLog(@"%.2f",result);
//一定不能忘了销毁当前的观察者
if(result==1){
[self.fileremoveObserver:selfforKeyPath:@"nowSize"];
}
}
-(void)begin{
[self.filestartCopy];
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。