-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 self
:anArgument
を保持していることは知っていますが、aObjectはどうなりますか?デタッチされたスレッド(aMethod :)の実行中にそれが存在することは確かですか?自己はによって保持されdetachNewThreadSelector
ますが、これは、メインスレッドのプールが保持されているために解放が遅れ、したがってclients
が存在し、したがってが存在することを意味しaObject
ますか?
または、-main
(NSOperation)スレッドは実行を終了し、 -aMethod
(NSThread)が終了する前に解放されるため、そこで使用するのは安全ではaObject
ありませんか?
本当の問題は次のとおりです。[NSThread detachNewThreadSelector:@selector(aMethod:) ...toTarget:self ...]
スレッド内から呼び出す場合、最後のスレッドは、自動解放されたインスタンス(clients
配列)が()で安全に使用できるようaMethod
に保持されself->aObject
ますか(弱い参照を介して)?