【问题标题】:Convert dispatch_data_t to NSString after a read operation读操作后将 dispatch_data_t 转换为 NSString
【发布时间】:2014-12-11 11:12:55
【问题描述】:

在我的小型 iOS 应用程序中,我有一个表示直方图的 CSV 文件。文件内容为:

标签0,值0

...

标签N,值N

在我的 ViewController 中,我以这种方式与 Grand Central Dispatch 异步读取文件:

//create the channel with which read the CSV file
dispatch_io_t ch = dispatch_io_create_with_path(DISPATCH_IO_STREAM, [[[NSBundle mainBundle] pathForResource:@"histogram1" ofType:@"csv"] UTF8String], O_RDONLY, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(int error) {

    if(!error){
        NSLog(@"Channel created!");
    }

});

//read the whole file
dispatch_io_read(ch, 0, SIZE_MAX, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(bool done, dispatch_data_t dataRead, int error) {

    if(!error && done){
        NSString *ma = ; //???
        NSLog(@"%@", ma);
    }

});

我想将dataReaddispatch_data_t 类型)转换为NSString,以提取代表直方图条形的值。

【问题讨论】:

    标签: ios objective-c csv asynchronous grand-central-dispatch


    【解决方案1】:

    有很多方法可以做到这一点,但您正在寻找的功能是dispatch_data_apply。假设您正在阅读的字符串是 UTF8,这应该可以工作:

    @interface NSString (FromDispatchData)
    
    + (instancetype)stringFromDispatchData: (dispatch_data_t)data;
    
    @end
    
    @implementation NSString (FromDispatchData)
    
    + (instancetype)stringFromDispatchData: (dispatch_data_t)data
    {
        if (!data)
            return nil;
    
        NSMutableString* str = [NSMutableString string];
    
        dispatch_data_apply(data, ^bool(dispatch_data_t region, size_t offset, const void *buffer, size_t size) {
            [str appendString: [[NSString alloc] initWithBytes:buffer length:size encoding: NSUTF8StringEncoding]];
            return true;
        });
    
        return [[self class] stringWithString: str];
    }
    
    @end
    

    【讨论】:

    • 是的,完美:dispatch_data_apply 正是我正在寻找的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 2017-03-08
    • 2016-01-17
    • 2012-02-29
    • 2011-02-04
    • 2011-04-24
    • 2013-10-19
    相关资源
    最近更新 更多