views:

148

answers:

2

Hello,

I am passing an object to a secondary thread using the following code:

 (void)login:(id)sender
{
  platformMsgs_LoginRequest *loginRequest = [[[platformMsgs_LoginRequest alloc] init] autorelease];
//more code...
 [NSThread detachNewThreadSelector:@selector(sendLoginRequest:) toTarget:self withObject:loginRequest];
//more code...
}

- (void)sendLoginRequest:(platformMsgs_LoginRequest *)loginRequest
 {
 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 [loginRequest retain];
 NetSuiteBinding *binding = [NetSuiteServiceSvc NetSuiteBinding];
 NetSuiteBindingResponse *response = [binding loginUsingParameters:loginRequest      applicationInfo:nil partnerInfo:nil];
 [self performSelectorOnMainThread:@selector(loginOperationCompleted:)   withObject:response waitUntilDone:NO];
 [loginRequest release];
 [pool drain];
 }

My question is, is autorelease the right way to handle the release of this object?. Once it is passed to the secondary thread I retain it and release it when I no longer need it.

However is it possible that the autorelease, releases the object before the secondary thread has a chance to retain it?. Do I have to create an ivar for this?, so that I can release the object in the performSelectorOnMainThread?. I no longer need the object after the login so an ivar doesn't seem like the right way to go. What is the best way to handle this?. Thank you.

-Oscar

+2  A: 

The documentation for detachNewThreadSelector:toTarget:withObject: answers your question:

The objects aTarget and anArgument are retained during the execution of the detached thread, then released.

So yes, you can autorelease the object or release it explicitly after calling detachNewThreadSelector. And you don't have to retain the object in the secondary thread.

Ole Begemann
Thank you, should have looked into the documentation =).
OscarMk
+1  A: 

From the docs.

detachNewThreadSelector:toTarget:withObject:

The objects aTarget and anArgument are retained during the execution of the detached thread, then released. The detached thread is exited (using the exit class method) as soon as aTarget has completed executing the aSelector method.

So you dont need to try this hard. Autorelease is fine here, and you should not need to retain it in the thread since the thread itself retains the argument and the target, and will release it when done.

Squeegy