Dispatch I/O 文件读取

来源:互联网 发布:王家卫表白方式 知乎 编辑:程序博客网 时间:2024/06/03 20:04

1.异步串行读取文件

   

    NSString *desktop =@"/Users/XXX/Desktop";

    NSString *path = [desktopstringByAppendingPathComponent:@"main.m"];

    dispatch_queue_t queue =dispatch_queue_create("queue",NULL);//当设置为并行队列时在读取文件时实际还是串行

    dispatch_fd_t fd =open(path.UTF8String,O_RDONLY, 0);

    dispatch_io_t io =dispatch_io_create(DISPATCH_IO_STREAM, fd, queue, ^(int error) {

        close(fd);

    });

    

    size_t water =1024*1024;

    dispatch_io_set_low_water(io, water);

    dispatch_io_set_high_water(io, water);

    longlong fileSize = [[NSFileManagerdefaultManager] attributesOfItemAtPath:patherror:nil].fileSize;

    NSMutableData *totalData = [[NSMutableDataalloc] init];

    dispatch_io_read(io,0, fileSize, queue, ^(bool done,dispatch_data_t  _Nullable data, int error) {

        if (error ==0) {

            size_t len =dispatch_data_get_size(data);

            if (len >0) {

                [totalData appendData:(NSData *)data];

            }

        }

        

        if (done) {

            NSString *str = [[NSStringalloc] initWithData:totalDataencoding:NSUTF8StringEncoding];

            NSLog(@"%@", str);

        }

    });


2.异步并行读取文件

    NSString *desktop =@"/Users/XXX/Desktop";

    NSString *path = [desktop stringByAppendingPathComponent:@"main.m"];

    dispatch_queue_t queue = dispatch_queue_create("queue",DISPATCH_QUEUE_CONCURRENT);

    dispatch_fd_t fd = open(path.UTF8String,O_RDONLY);

    dispatch_io_t io = dispatch_io_create(DISPATCH_IO_RANDOM, fd, queue, ^(int error) {

        close(fd);

    });

    

    off_t currentSize =0;

    long long fileSize = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil].fileSize;

    size_t offset =1024*1024;

    dispatch_group_t group =dispatch_group_create();

    NSMutableData *totalData = [[NSMutableData alloc] initWithLength:fileSize];

    for (; currentSize <= fileSize; currentSize += offset) {

        dispatch_group_enter(group);

        dispatch_io_read(io, currentSize, offset, queue, ^(bool done,dispatch_data_t  _Nullable data, int error) {

            if (error ==0) {

                size_t len =dispatch_data_get_size(data);

                if (len >0) {

                    constvoid *bytes = NULL;

                    (void)dispatch_data_create_map(data, (constvoid **)&bytes, &len);

                    [totalData replaceBytesInRange:NSMakeRange(currentSize, len)withBytes:bytes length:len];

                }

            }

            

            if (done) {

                dispatch_group_leave(group);

            }

        });

    }

    

    dispatch_group_notify(group, queue, ^{

        NSString *str = [[NSStringalloc] initWithData:totalDataencoding:NSUTF8StringEncoding];

        NSLog(@"%@", str);

    });



0 0
原创粉丝点击