我有一个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方法保留了self
和withObject:anArgument
,但aObject会发生什么??是否确定在执行分离线程(aMethod:)的过程中会存在?Self被detachNewThreadSelector
保留,这是否意味着-main线程的池将被延迟释放,因为它被保留了,因此clients
将存在,从而aObject
将存在
或者-main
(NSOperation)线程将在-aMethod
(NSThread)完成之前完成执行并释放,所以在那里使用aObject
是不安全的?
真正的问题是:当从线程内部调用[NSThread detachNewThreadSelector:@selector(aMethod:) ...toTarget:self ...]
时,最后一个线程是否以其自动释放的实例(clients
数组)可以安全地在aMethod
(self->aObject
)中使用的方式保留(比方说通过弱引用)?
您的方法看起来非常不稳定,但我不是多线程专家,所以我可能错了。你的客户端数组在主自动释放池中,你不能保证它会等到你的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];
}
使用这种方法,客户端数组位于线程的自动释放池中。