// Method called when a button is clicked
- (void)handleClickEvent {
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self backgroundProcessing];
});
// Some code to update the UI of the view
....
[self updateUI];
....
}
1) handleClickEvent is called on the main thread when a button on the view is pressed.
2) I used dispatch_sync() because the following code that updates the UI of the view cannot be done until a variable in the backgroundProcessing method is calculated.
3) I used dispatch_get_global_queue in order to get the backgroundProcessing off the main thread. (following the rule: generally put background processing off main thread and generally put code that affect the UI on the main thread).
My question is: Does the backgroundProcessing method “hang” the main thread until it is complete since I am using dispatch_sync?
EDIT:
Based on the answer below i have implemented this solution:
- (void)handleClickEvent {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self backgroundProcessing];
dispatch_async(dispatch_get_main_queue(), ^{
[self updateUI];
});
});
}
solution from this link: Completion Callbaks
Yes, dispatch_sync will block until the task is complete. Use dispatch_async and when the job is complete have it post a block back to the main queue to update the view.