Created
September 11, 2009 15:54
-
-
Save AlanQuatermain/185377 to your computer and use it in GitHub Desktop.
Example of modifying synchronous code to asynchronous with GCD.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Before: | |
- (IBAction) optimizeDataObject: (MyDataObject *) obj | |
{ | |
// going to start work, so show the user that something's happening | |
[self.progressIndicator startAnimating]; | |
// these two are *usually* quick -- unless the user opens a 1GB file. | |
// because this is happening in an event handler, it'll stall the event loop, which | |
// causes the good ol' spinning beachball of death | |
[self pruneDuplicatesInDataObject: obj]; | |
[self sortContentsOfDataObject: obj]; | |
// all done, stop showing activity | |
[self.progressIndicator stopAnimating]; | |
} | |
// After: | |
- (IBAction) optimizeDataObject: (MyDataObject *) obj | |
{ | |
// going to start work, so show the user that something's happening | |
[self.progressIndicator startAnimating]; | |
// these two are *usually* quick -- unless the user opens a 1GB file. | |
// we'll run this bit in the background instead: | |
dispatch_async( dispatch_get_global_queue(0, 0), ^{ | |
[self pruneDuplicatesInDataObject: obj]; | |
[self sortContentsOfDataObject: obj]; | |
// all done, stop showing activity | |
// UI updates should happen on the main thread, so we'll run it there: | |
dispatch_async( dispatch_get_main_queue(), ^{ | |
[self.progressIndicator stopAnimating]; | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment