views:

267

answers:

2

I would like to send an object back to the main thread from worker thread. However do auto-release pools work between threads? Is there anything wrong with the following code:

-(void)mainThreadReceiveResult:(id)response
{
  [response retain];
    /* Do some stuff with response */
  [response release];
}


-(void)workerThreadDoWork
{

 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

 response * response = [[[response alloc] init] autorelease];
 response->someData = [self getSomeData];

 [delegate performSelectorOnMainThread:@selector(receiveResult:) withObject:response waitUntilDone:NO];

 [pool release];    

}

Seems to work fine. However is it possible that the worker thread could reach [pool release] before the main thread is able to retain it?

A: 

This may answer your question.

Here's what he did to solve the problem. The explanation is given in that link.

- (void)runSomethingThatWillFail:(NSError **)error {
   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   NSArray *directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/BOGUS" error:error];
   [*error retain];
   [pool release];
   [*error autorelease];
}
Marc W
+7  A: 

Your code shouldn't crash: performSelectorOnMainThread: retains its arguments until after the selector finishes, so your retain/release pair is superfluous.

See the documentation:

This method retains the receiver and the arg parameter until after the selector is performed.

Also: you should probably [pool drain] instead of [pool release].

Jim Puls
ok thanks for the tip
Ben Reeves