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
Threads who have finished their jobs will die. It won't consume any more CPU time. You can use jstack to check how many threads are active running in your java process.
For a thread to call wait() or notify(), the thread has to be the owner of the lock for that object. Otherwise, a runtime error occur and the rest of code is not executed.
synchronized keyword is used to make the class or method thread-safe which means only one thread can have lock of synchronized method and use it, other threads have to wait till the lock releases and anyone of them acquire that lock.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With