2011-09-19 78 views
0

在我的一個函數中,我有一個while循環,可能需要臨時創建一個對象。我的代碼如下所示:我什麼時候可以釋放一個對象?

while(c < end){ 
    if(specialCase){ 
     Object *myObject = [Object alloc]; 
     //do stuff with myObject 
     //I tried [myObject dealloc] here, but it crashed when this method was called. 
    } 
    c++; 
} 

該代碼正常工作,但我擔心內存泄漏。我想知道是否和如何我應該dealloc myObject。

回答

5

你從不直接調用Dealloc。

你打電話發佈,當保留計數達到0時,dealloc將在對象上調用。

+0

謝謝!我試圖在dealloc之前的某個時刻調用release,並得到錯誤的訪問錯誤。我想現在我知道爲什麼。 – WolfLink

1

你不應該直接調用dealloc方法,它們要麼allocedretain將調用dealloc含蓄調用對象的release,如果保留計數對象滿足與條件由的iOS系統放(通常如果保留計數ZERO爲對象)。

閱讀dealloc方法的蘋果文檔中NSObject類,也經過Memory Management Programming Guide客觀-C

0

試試這個

while(c < end){ 
if(specialCase){ 
Object *myObject = [[Object alloc] autorelease]; 
    //do stuff with myObject 
    //I tried [myObject dealloc] here, but it crashed when this method was called. 
} 
c++; 

}

0

你也許可以嘗試使用智能指針。 這應該照顧垃圾收集和任何異常處理。另外,Boost庫可以移植到ios上。

相關問題