zoukankan      html  css  js  c++  java
  • 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];
    }
  • 相关阅读:
    Spring security中的BCryptPasswordEncoder方法对密码进行加密与密码匹配
    Eclipse导入SpringBoot项目pom.xml第一行报错Unknown error
    分库分表理论概述
    什么是乐观锁,什么是悲观锁
    oracle中的索引查看
    手动实现tail
    KNN理论
    矩阵以及向量
    numpy常用的几个小函数
    线性回归
  • 原文地址:https://www.cnblogs.com/tangshiguang/p/6753609.html
Copyright © 2011-2022 走看看