Grand Central Dispatch は優れており、コードの量を削減しますが、バックグラウンド スレッドで何かを実行できないのはなぜですか?
私が何を意味するかを示すサンプルアプリケーションを作成しました(コメントされた作業はありません):
- (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];
}
これ[NSThread sleepForTimeInterval:3];
は、デフォルトの UI 機能をシミュレートするためのものです。たとえば、あるナビゲーション ビューから別のナビゲーション ビューに切り替えている場合などです。
新しいビュー ベースのアプリケーションにコードをコピーし、2 つのボタンを作成して接続するだけです。