Skip to content

Instantly share code, notes, and snippets.

@edom18
Created April 3, 2014 05:14
Show Gist options
  • Select an option

  • Save edom18/9948620 to your computer and use it in GitHub Desktop.

Select an option

Save edom18/9948620 to your computer and use it in GitHub Desktop.
NSOperationを使って並列処理をするシンプルなサンプル ref: http://qiita.com/edo_m18/items/c121d0cb42a6e20cefbd
// 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
// 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
[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