我有其中其-main方法內我使用[NSThread detachNewThreadSelector:@selector(aMethod:) toTarget:self withObject:anArgument];
目標C線程
aObject
(我的NSOperation子類的實例變量)是一種弱引用一個autoreleased陣列的對象的的NSOperation該方法 - 主內返回...
-(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
)所使用的最後一個線程(可以通過弱引用說)?
感謝您的回覆。我可能會錯過提到許多事情和處理髮生在'-main'線程中設置'self-> aObject'之前和之後。所以我想要這兩個線程並行執行。我不會使用兩個線程,否則,我? – Vassilis 2011-06-04 01:18:13