I have an NSOperation where inside its -main method I use [NSThread detachNewThreadSelector:@selector(aMethod:) toTarget:self withObject:anArgument];
aObject
(instance variable of my NSOperation subclass) is a weak reference to an object of an autoreleased array returned inside the -main method...
-(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];
}
I know that NSThread's detachNewThreadSelector method retains self
and withObject:anArgument
, but what happens to aObject ?? Is it sure that will exist during the execution of the detached thread (aMethod:) ? Self is retained by detachNewThreadSelector
, does this mean that the pool of the -main thread will be delayed released since it is retained and thus the clients
will exist and thus the aObject
will exist ?
Or the -main
(NSOperation) thread will finish execution and released before -aMethod
(NSThread) finishes so it's unsafe to use aObject
there ?
The real question is: When calling [NSThread detachNewThreadSelector:@selector(aMethod:) ...toTarget:self ...]
from inside a thread, does the last thread being retained in a way that its autoreleased instances (clients
array) are safe to be used in aMethod
(self->aObject
) (lets say via weak references) ?