我使用以下代码将对象传递给辅助线程:
(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];
}
我的问题是,autorelease 是处理该对象释放的正确方法吗?一旦它被传递到辅助线程,我就保留它并在不再需要它时释放它。
但是,自动释放是否有可能在辅助线程有机会保留该对象之前释放该对象?我是否必须为此创建一个ivar?以便我可以在performSelectorOnMainThread 中释放该对象?登录后我不再需要该对象,因此 ivar 似乎不是正确的方法。处理这个问题的最佳方法是什么?谢谢。
-奥斯卡
最佳答案
detachNewThreadSelector:toTarget:withObject:
的文档回答了您的问题:
The objects aTarget and anArgument are retained during the execution of the detached thread, then released.
所以是的,您可以自动释放该对象或在调用 detachNewThreadSelector 后显式释放它。而且您不必在辅助线程中保留该对象。
关于iphone - 何时释放/保留传递给辅助线程的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2233233/