sup*_*cio 2 csv asynchronous objective-c grand-central-dispatch ios
在我的小型 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);
}
});
Run Code Online (Sandbox Code Playgroud)
我想将dataRead
(类型dispatch_data_t
)转换NSString
为提取代表直方图条形的值。
有很多方法可以做到这一点,但您正在寻找的功能是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
Run Code Online (Sandbox Code Playgroud)