我有一个 NSOperation 在我使用的 -main 方法中[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 方法保留self
和 withObject: anArgument
,但是 aObject 会发生什么?是否确定在执行分离线程(aMethod:) 期间会存在?自我被保留detachNewThreadSelector
,这是否意味着-主线程的池将被延迟释放,因为它被保留,因此clients
将存在,因此aObject
将存在?
或者-main
(NSOperation)线程将在-aMethod
(NSThread)完成之前完成执行并释放,所以在aObject
那里使用不安全?
真正的问题是:当从线程内部调用[NSThread detachNewThreadSelector:@selector(aMethod:) ...toTarget:self ...]
时,最后一个线程是否被保留,其自动释放的实例(clients
数组)可以安全地在aMethod
( self->aObject
) 中使用(让我们说通过弱引用)?