Grand Central Dispatch is great and reduces the amount of code but why I cannot run something on a background thread?
I have made a sample application to show what I mean (none of the commented work):
- (IBAction)performSel {
[self performSelectorInBackground:@selector(doStuff) withObject:nil];
[NSThread sleepForTimeInterval:3];
[[self.view.subviews lastObject] removeFromSuperview];
}
- (IBAction)gcd {
dispatch_async(dispatch_queue_create("myGCDqueue", NULL), ^(void) {
//dispatch_sync(dispatch_queue_create("myGCDqueue", NULL), ^(void) {
//dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
//dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
//dispatch_async(dispatch_get_main_queue(), ^(void) {
//dispatch_sync(dispatch_get_main_queue(), ^(void) {
[self doStuff]; // only for readability, will move the code on success
});
[NSThread sleepForTimeInterval:3];
[[self.view.subviews lastObject] removeFromSuperview];
}
- (void)doStuff {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
UIView *abortingView = [[UIView alloc]initWithFrame: self.view.bounds];
abortingView.backgroundColor = [UIColor whiteColor];
abortingView.alpha = 0.7;
[self.view insertSubview:abortingView atIndex:10];
[abortingView release];
[pool drain];
}
the [NSThread sleepForTimeInterval:3];
is to simulate a default UI functionality. For example if someone is switching from one navigation view to another.
Simply copy the code in a new view based application, create two buttons and connect them.