溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

KVO如何實(shí)現(xiàn)自定義文件復(fù)制進(jìn)度效果

發(fā)布時(shí)間:2021-07-21 14:41:08 來(lái)源:億速云 閱讀:107 作者:小新 欄目:移動(dòng)開發(fā)

小編給大家分享一下KVO如何實(shí)現(xiàn)自定義文件復(fù)制進(jìn)度效果,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

一、創(chuàng)建文件

說(shuō)明:自定義文件類,通過(guò)NSFileManager 以及NSFileHandle 實(shí)現(xiàn)文件的創(chuàng)建和copy,為了控制內(nèi)存的并發(fā)使用,通過(guò)控制每次賦值的固定長(zhǎng)度來(lái)分多次復(fù)制:

NSString * path=NSHomeDirectory();
  path =[path stringByAppendingPathComponent:@"deskTop/Boby.m"];
  
  NSString * target=NSHomeDirectory();
  target =[target stringByAppendingPathComponent:@"deskTop/target.m"];
  
  NSFileManager * manager=[NSFileManager defaultManager];
  
  
  //校驗(yàn)并且創(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];

二、設(shè)置觀察者

說(shuō)明:自定義使用者,通過(guò)設(shè)置觀察者來(lái)動(dòng)態(tài)觀察當(dāng)前文件copy的進(jìn)度并展示到控制臺(tái)或者輸出到UI,并提供方法接口,啟動(dòng)文件拷貝。

- (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);
  //一定不能忘了銷毀當(dāng)前的觀察者
  if(result==1){
    [self.file removeObserver:self forKeyPath:@"nowSize"];
  }
}

- (void) begin{
  [self.file startCopy];
}

看完了這篇文章,相信你對(duì)“KVO如何實(shí)現(xiàn)自定義文件復(fù)制進(jìn)度效果”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

kvo
AI