1


-mainメソッド内で使用するNSOperationがあります[NSThread detachNewThreadSelector:@selector(aMethod:) toTarget:self withObject:anArgument];

aObject(私のNSOperationサブクラスのインスタンス変数)は、-mainメソッド内に返される自動解放された配列のオブジェクトへの弱参照です。

-(void)main {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSArray *clients = [group produceClients]; // clients array is an autorelease instance
    self->aObject = [clients objectAtIndex:3]; // a weak reference, Lets say at index three!

    [NSThread detachNewThreadSelector:@selector(aMethod:) 
                             toTarget:self 
                           withObject:@"I use this for another thing"];

    // Do other things here that may take some time

    [pool release];
}

-(void)aMethod:(NSString*)aStr {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // aStr object is reserved for another functionality
    // I know that I could pass a NSDictionary with a number of entries, which would be
    // retained by `detachNewThreadSelector` but then ... 
    // I wouldn't have to ask this question ! :)

    // Do several things with aObject, which is a weak reference as described above.
    NSLog(@"%@", [self->aObject.id]);
    // Is it safe ?

    [pool release];
}

NSThreadのdetachNewThreadSelectorメソッドがwithObject selfanArgumentを保持していることは知っていますが、aObjectはどうなりますか?デタッチされたスレッド(aMethod :)の実行中にそれが存在することは確かですか?自己はによって保持されdetachNewThreadSelectorますが、これは、メインスレッドのプールが保持されているために解放が遅れ、したがってclientsが存在し、したがってが存在することを意味しaObjectますか?
または、-main(NSOperation)スレッドは実行を終了し、 -aMethod(NSThread)が終了する前に解放されるため、そこで使用するのは安全ではaObjectありませんか?

本当の問題は次のとおりです。[NSThread detachNewThreadSelector:@selector(aMethod:) ...toTarget:self ...]スレッド内から呼び出す場合、最後のスレッドは、自動解放されたインスタンス(clients配列)が()で安全に使用できるようaMethodに保持されself->aObjectますか(弱い参照を介して)?

4

1 に答える 1

0

あなたのアプローチは非常に不安定に見えますが、私はマルチスレッドの専門家ではないので、間違っている可能性があります. クライアント配列はメインの自動解放プールにあり、aMethod スレッドが完了するまで待機することは保証できません。これはどうですか:

-(void)main {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    [NSThread detachNewThreadSelector:@selector(aMethod:) 
                             toTarget:self 
                           withObject:@"I use this for another thing"];

    [pool release];
}

-(void)aMethod:(NSString*)aStr {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSArray *clients = [group produceClients]; // clients array is an autorelease instance
    self->aObject = [clients objectAtIndex:3]; // a weak reference, Lets say at index three!

    [pool release];
}

このアプローチでは、clients 配列はスレッドの autorelease プールにあります。

于 2011-06-04T01:00:01.003 に答える