我试图让 - [的NSString stringWithContentsOfURL:编码:错误:]异步的,由后台线程运行它,synchronically:使stringWithContentsOfURL异步 - 是否安全?
__block NSString *result;
dispatch_queue_t currentQueue = dispatch_get_current_queue();
void (^doneBlock)(void) = ^{
printf("done! %s",[result UTF8String]);
};
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
(unsigned long)NULL), ^(void) {
result = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com/"] encoding:NSUTF8StringEncoding error:nil];
dispatch_sync(currentQueue, ^{
doneBlock();
});
});
它的做工精细,最重要的是,它的异步。
我的问题是,如果这样做是安全的,或者可能有任何线程问题等?
在此先感谢:)
干杯!我不知道这是可能的:P – JonasG 2012-07-23 23:30:12
首先,我认为这将在主队列上工作,因为有['NSOperationQueue mainQueue]',但是我看到'sendAsynchronousRequest'。所以这不应该阻止UI更新。 – 2016-08-11 10:02:36