Consider this code:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
UIGraphicsBeginImageContext(self.bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
//perform some drawing into this context
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
dispatch_sync(dispatch_get_main_queue(), ^{
self.imageView.image=viewImage;
});
});
Why is it necessary to get the main queue at the end before updating an object with the results of the routine? Why not just update within the queue queue ?
Anything that touches the GUI has to be on the main thread. (The main dispatch queue is guaranteed to be running on the main thread.) That part of Cocoa/Cocoa Touch is not thread-safe.
See “Threads and Your User Interface” in the Threading programming guide:
The image view is part of the GUI, so you need to set its properties only on the main thread.
If you were updating an array, for example, it would not be required that you do it on the main thread (you’d just have to watch out for reads or other writes happening simulataneously).