Skip to content

Instantly share code, notes, and snippets.

@AlanQuatermain
Created September 11, 2009 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlanQuatermain/185377 to your computer and use it in GitHub Desktop.
Save AlanQuatermain/185377 to your computer and use it in GitHub Desktop.
Example of modifying synchronous code to asynchronous with GCD.
// 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