NSOperationを使用したバックグラウンド処理
iOSでバックグラウンド処理を行う方法です。裏でこっそりダウンロードとか, ファイルのチェックなどバックグラウンドで処理したい要求がもちろんあるでしょう。
ここでは簡単なNSOperationQueueを使った方法を説明します。
手順
- NSOperationの拡張クラスを作成する
- 利用する
NSOperationの拡張クラスを作成する
BackgroundTask.h
@interface BackgroundTask : NSOperation @end
BackgroundTask.m
@implementation BackgroundTask -(void)main { // Background [[NSOperationQueue mainQueue] addOperationWithBlock:^{ // main-thread }]; } -(BOOL)isConcurrent { return YES; } @end
実装するのは, -(void)mainという, メソッドです。
これがバックグラウンドの処理に該当します。
ここから直接UIには, アクセスできません。対処法は下に。
それから, CoreDataも要注意。Shared contextを使うと落ちます。FileManager もdefaultではないやつを作ることをおすすめします。
isConcurrentをオーバーライドして, mainQueueで行うかそうでないかを選択できます。
利用する
NSOperationQueueを作成してQueueへNSOperationの拡張クラスを入れます。あとはQueueが処理してくれます。
NSOperationQueue *queue = [[NSOperationQueue alloc] init]; BackgroundTask *operation = [[BackgroundTask alloc] init]; [queue addOperation:operation];
main-thread
別スレッドで実行したものをmain-threadの制御にするには
[[NSOperationQueue mainQueue] addOperationWithBlock:^{ // main-thread }];
で処理をかきます。ブロックの中ですね。