NSOperationQueue
並列処理
iOSで並列処理といえばGCDとNSOperation/NSOperationQueueの2種類があります。 GCDはCベース、NSOperation/NSOperationQueueはObjective-CベースのAPIです。
直列で処理を実行していると、先の重い処理が終わらないとUIの更新が行われず、ユーザを待たせることにつながってしまいます。
今回はNSOperation/NSOperationQueueの方を使って、サイトから文字列を取得し、それをUITextViewに表示するサンプルを紹介します。
並列処理
NSOperationQueue* queue = [NSOperationQueue new]; [queue addOperationWithBlock:^{ // 重い処理(URLにアクセスしそこから文字列を取得) NSURL* url = [NSURL URLWithString:@"http://www.apple.com/jp/ipad/"]; NSString* response = [NSString stringWithContentsOfURL:url usedEncoding:nil error:nil]; // UIの更新(必ずmainから行う) [[NSOperationQueue mainQueue] addOperationWithBlock:^{ self.textView.text = response; }]; }];