2012年2月22日水曜日

[objective-c] objective-cでAsyncTaskみたいな非同期処理

testOperation.h
@interface testOperation : NSOperation {
    BOOL isExecuting, isFinished;
}
@end

testOperation.m
#import "testOperation.h"

@implementation testOperation

-(void) dealloc {
    [super dealloc];
}
- (BOOL)isExecuting {
    return isExecuting;
}
- (BOOL)isFinished {
    return isFinished;
}

/**
 * 処理メイン
 */
-(void) main {
    LOG_METHOD;
    for (;;) {
        // 〜適当なループ処理など
        if ([self isCancelled])
                break; // キャンセルの場合にループを抜けるなりreturnするなり
    }
}

@end


呼び出し元
- (void) hogehoge {
    NSOperationQueue * _queue;
    _queue = [[NSOperationQueue alloc] init];
    // 1つ目のリクエスト
    testOperation *ope1 = [[[testOperation alloc] init]retain];;
    [ope1 autorelease];
    // 終了監視
    [ope1 addObserver:self forKeyPath:@"isFinished" 
                   options:NSKeyValueObservingOptionNew context:nil];
    // キュー実行
    [_queue addOperation:ope1];
}

- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object 
                        change:(NSDictionary*)change context:(void*)context
{
    LOG_METHOD;
    // タスク終了時の処理
    // 〜〜〜〜

    // キー値監視を解除する
    [object removeObserver:self forKeyPath:keyPath];
}

0 件のコメント:

コメントを投稿