2010-02-09 76 views
5

我使用下面的代碼傳遞一個對象來輔助線程:何時釋放/保留傳遞給輔助線程的對象?

(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似乎不是正確的路。處理這個問題的最好方法是什麼?謝謝。

-Oscar

回答

5

detachNewThreadSelector:toTarget:withObject:文檔回答你的問題:

aTarget和anArgument的分離線程的執行過程中被保留的對象,然後釋放。

所以是的,您可以在調用detachNewThreadSelector之後自動釋放對象或顯式釋放它。而且您不必在輔助線程中保留該對象。

+0

謝謝,應該查看文檔=)。 – 2010-02-09 23:26:27

1

來自文檔。

detachNewThreadSelector:toTarget:withObject:

目的aTarget和anArgument是 的 分離線程的執行期間保持,然後釋放。一旦目標 完成執行aSelector 方法,退出 分離線程(使用 退出類方法)。

所以你不需要努力嘗試。在這裏Autorelease沒問題,你不需要在線程中保留它,因爲線程本身保留了參數和目標,並在完成時釋放它。