Created
April 3, 2014 05:14
-
-
Save edom18/9948620 to your computer and use it in GitHub Desktop.
NSOperationを使って並列処理をするシンプルなサンプル ref: http://qiita.com/edo_m18/items/c121d0cb42a6e20cefbd
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // NOTOperation.m | |
| @interface NOTOperation () | |
| @property (assign, nonatomic) BOOL isFinished; | |
| @property (assign, nonatomic) BOOL isExecuting; | |
| @end | |
| //////////////////////////////////////////////////// | |
| @implementation NOTOperation | |
| // KVO対象のキーを指定 | |
| + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key | |
| { | |
| if ([key isEqualToString:@"isExecuting"] || | |
| [key isEqualToString:@"isFinished"]) { | |
| return YES; | |
| } | |
| return [super automaticallyNotifiesObserversForKey:key]; | |
| } | |
| // オペレーション実行 | |
| - (void)start | |
| { | |
| // 処理中のフラグ | |
| self.isExecuting = YES; | |
| // スレッド処理開始 | |
| // 分かりやすいようにスリープを入れる | |
| [NSThread sleepForTimeInterval:2.0]; | |
| // 処理中フラグをオフ | |
| self.isExecuting = NO; | |
| // 処理終了フラグ | |
| self.isFinished = YES; | |
| } | |
| @end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // NOTClient.m | |
| @interface NOTClient () | |
| @property (strong, nonatomic) NOTOperation *operation; | |
| @property (strong, nonatomic) NSOperationQueue *queue; | |
| @end | |
| ////////////////////////////////////////////////////////// | |
| @implementation NOTClient | |
| - (instancetype)init | |
| { | |
| if (self = [super init]) { | |
| self.operation = [[NSOperation alloc] init]; | |
| self.queue = [[NSOperationQueue alloc] init]; | |
| } | |
| return self; | |
| } | |
| - (void)performMethod | |
| { | |
| [self.operation addObserver:self | |
| forKeyPath:@"isFinished" | |
| options:NSKeyValueObservingOptionNew | |
| context:nil]; | |
| [self.queue addOperation:self.operation]; | |
| } | |
| - (void)observeValueForKeyPath:(NSString *)keyPath | |
| ofObject:(id)object | |
| change:(NSDictionary *)change | |
| context:(void *)context | |
| { | |
| // do something. | |
| } | |
| @end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| [self.queue addObserver:self | |
| forKeyPath:@"operationCount" | |
| options:NSKeyValueObservingOptionNew | |
| context:nil]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment