KVO實現自訂檔案複製進度展示,kvo自訂進度展示

來源:互聯網
上載者:User

KVO實現自訂檔案複製進度展示,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];}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.