ホーム > Cocoa, Mac, Objective-C > NSThread detachNewThreadSelector:toTarget:withObject:

NSThread detachNewThreadSelector:toTarget:withObject:

NSThread の detacheNewThreadSelector:toTarget:withObject: についてメモ。

例えば次のような意味の無いコードを実行すると、NSAutoreleaseNoPool のエラーが発生する。

- (void) hogeThread {
    NSMutableArray *anArray = [NSMutableArray array];
    int i = 0;
    while (isInThread) {
        [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
        [anArray addObject: [NSString stringWithFormat:@"%d". i++]];
    }
    [NSThread exit];
}

- (void) stopThread {
    isInThread = NO;
} 

- (void) doThread {
    isInThread = YES;
    [NSThread detachNewThreadSelector:@selector(hogeThread) 
                             toTarget:self 
                           withObject:nil];
} 

まず、NSMutableArray はクラスメソッド array によって autorelease 済みの状態で用意される。

また、NSStringも同様にクラスメソッド stringWithFormat: によって autorelease 済みで用意される。

通常、アプリケーションはメインスレッド用にAutoreleasePoolをひとつ持っている。

新しいスレッドを用意した場合、別途AutoreleasePoolを用意してやらないと、NSMutableArray とNSString でメモリリークが発生する。

- (void) hogeThread {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSMutableArray *anArray = [NSMutableArray array];
    int i = 0;
    while (isInThread) {
        [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
        [anArray addObject: [NSString stringWithFormat:@"%d". i++]];
    }
    [NSThread exit];

    [pool release];
}

これでOK。

カテゴリー: Cocoa, Mac, Objective-C タグ:
  1. コメントはまだありません。
  1. トラックバックはまだありません。