KVO實現(xiàn)自定義文件復制進度效果
本文實例為大家分享了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];
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
iOS App使用設計模式中的模板方法模式開發(fā)的示例
這篇文章主要介紹了iOS應用使用設計模式中的模板方法模式開發(fā)的示例,例子代碼為Objective-C語言,文中還與Java的相關實現(xiàn)進行類比,需要的朋友可以參考下2016-03-03
iOS從App跳轉至系統(tǒng)設置菜單各功能項的編寫方法講解
這篇文章主要介紹了iOS從App跳轉至系統(tǒng)設置菜單各功能項的編寫方法講解,示例代碼為傳統(tǒng)的Objective-C,需要的朋友可以參考下2016-04-04
iOS的UI開發(fā)中Modal的使用與主流應用UI結構介紹
這篇文章主要介紹了iOS的UI開發(fā)中Modal的使用與主流應用UI結構,代碼基于傳統(tǒng)的Objective-C,需要的朋友可以參考下2015-12-12
iOS小數(shù)取整的方法(ceil?floor?round)示例
這篇文章主要為大家介紹了iOS小數(shù)取整的方法(ceil?floor?round)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09
IOS開發(fā)代碼分享之用nstimer實現(xiàn)倒計時功能
在制作IOS項目中,我們經常要用到倒計時功能,今天就分享下使用nstimer實現(xiàn)的倒計時功能的代碼,希望對大家能有所幫助2014-09-09

