So every junior dev like myself is told to use dispatch_sync/async for fear of the main/background thread monster.
I get it but I'm not clear on the usage cases because documentation and blogs only ever mention dispatch_sync as it applies to network requests. They often say use it when updating the UI but what exactly defines updating the UI?
Should I not even be using dispatch_async at all in the cases below? How about the generic main_queue? global_queue?
What about these use cases?
Static notification pops up for a New Friend Request and taps the View Profile button i.e.
User taps Accept Friend button and is sent to a controller via modal segue that displays a cool "OK checkmark" animation i.e.
After user taps the cool animated OK button they are sent to the main initial VC with the typical vertical menu. The OK button has technically updated the UI with 160 frames so should that stuff be inside of a dispatch?
Also I've read that you should also code to avoid a hang if thread is already on main thread i.e.
I get it but I'm not clear on the usage cases because documentation and blogs only ever mention dispatch_sync as it applies to network requests. They often say use it when updating the UI but what exactly defines updating the UI?
Should I not even be using dispatch_async at all in the cases below? How about the generic main_queue? global_queue?
What about these use cases?
Static notification pops up for a New Friend Request and taps the View Profile button i.e.
Code:
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0)) { [unowned self] in
if let notificationIdentifier = identifier {
if notificationIdentifier == "ViewProfileButtonAction" {
self.pushControllerWithName("UserProfileController", context: nil)
}
}
}
User taps Accept Friend button and is sent to a controller via modal segue that displays a cool "OK checkmark" animation i.e.
Code:
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0)) { [unowned self] in
self.presentControllerWithName("OKController", context: nil)
}
After user taps the cool animated OK button they are sent to the main initial VC with the typical vertical menu. The OK button has technically updated the UI with 160 frames so should that stuff be inside of a dispatch?
Code:
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { [unowned self] in
self.buttonGroup.setBackgroundImageNamed("frame")
self.buttonGroup.startAnimatingWithImagesInRange(NSRange(location: 0, length: 159), duration: 2, repeatCount: 1)
self.buttonGroup.setAlpha(0.60)
}
}
Code:
void runOnMainQueueWithoutDeadlocking(void (^block)(void)) { if ([NSThread isMainThread]) { block(); } else { dispatch_sync(dispatch_get_main_queue(), block); } }
runOnMainQueueWithoutDeadlocking(^{ //Do stuff });
Last edited: