2011-02-15 96 views
1

我是iphone編程的新手。任何幫助將不勝感激:)當從回調函數中執行線程時發生「Just Leaking」

一切正常,當我從一個OBJ-C方法或這樣的C函數內啓動一個新的NSThread:

[NSThread detachNewThreadSelector:@selector(hello) toTarget:thisSelf withObject:nil]; 

(thisSelf =自我,我使用這以便能夠從一個C函數啓動線程)

但是,如果我有一個C調用從一個單獨的C線程啓動此NSThread而不是(以完全相同的方式)調用的函數,我得到「NSThread自動釋放,沒有到位 - 只是泄漏「

爲什麼泄漏?我無法弄清楚如何避免這種情況,因爲在「hello」方法中創建一個NSAutoreleasePool似乎並不能解決這個問題。

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
// code of method "hello" here 
[pool release]; 

任何見解/建議?

回答

3

的問題是,+detachNewThreadSelector:...創建一個自動釋放NSThread對象,所以你分開發送該消息的C線程也需要一個自動釋放池。您可以通過明確創建NSThread對象避免這種情況:

NSThread* newThread = [[NSThread alloc] initWithTarget: thisSelf 
               selector: @selector(hello) 
               object: nil]; 
[newThread start]; 
[newThread release]; // this might not be OK. You might need to wait until the thread is finished 

雖然,init方法的內部可能需要一個自動釋放池太在這種情況下,你只需要創建一個。

如果您使用posix線程創建C線程,那麼您在啓動第一個Posix線程時需要notify the Cocoa framework that the application is now multithreaded

+0

相關的釋放問題:http://stackoverflow.com/questions/1151637/when-is-it-safe-to-release-an-nsthread – Chuck 2011-02-15 18:31:16

0

你的執行你好lloks罰款。

未來

上任何符號,它是(?NSAutoreleaseNoPool),並告訴我休息:哪個線程這個從叫什麼?

我懷疑你可能不會有一個自動釋放池在其中創建在輔助線程的線程設置。

如果沒有,它是線程,那麼你沒有創建自動釋放池早就夠了。

(更多的代碼,將有助於如果不解決這個問題你)

0

試圖改變這樣:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
[NSThread detachNewThreadSelector:@selector(hello) toTarget:thisSelf withObject:nil]; 
[pool drain]; 
+0

這實際上也消除了泄漏。謝謝 – ntcio 2011-02-15 21:02:14

相關問題