I tried to make [NSString stringWithContentsOfURL: encoding: error:] asynchronous by executing it a-synchronically from the background thread:
__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(); }); });
His work is beautiful and, most importantly, asynchronous.
My question is, is it safe to do this or can there be problems with threads, etc.?
Thanks in advance:)
source share