2012-06-05 63 views
0

據,如果我們有以下屬性的靜態分析器:關於存儲器管理在目標C

@property (retain, nonatomic) SomeObject * object; 

然後我們分配屬性,像這樣:

self.object = [SomeObject alloc] init]; 

泄漏發生。這是有道理的,因爲alloc init將+1保留計數加1,然後retain屬性也增加保留計數。這裏最好的解決方案是什麼?通常我只需要添加一個自動釋放,像這樣:

self.object = [[SomeObject alloc] init] autorelease]; 

但有時這對我造成的問題,我結束了在釋放導致我的應用程序崩潰的對象。我沒有任何具體的例子,但現在我還記得我不得不採取一些自動釋放導致應用程序崩潰的。有什麼我在這裏失蹤?

編輯:我現在我正在運行到問題有一個具體的例子。

NSMutableArray *newData = [NSMutableArray array]; 

    //If this is true then we are showing all of the items in that level of hierarchy and do not need to show the summary button. 
    if (!(contextID.count >= 1 && [[contextID objectAtIndex:contextID.count - 1] isEqual:[NSNull null]]) && contextID.count != 0) 
    { 
     GeographyPickerItem * firstItem = [[GeographyPickerItem alloc] init]; 

     firstItem.primaryString = [NSString stringWithString:@"Summary"]; 
     firstItem.subString = [NSString stringWithString:@""]; 
     firstItem.isSummaryItem = YES; 

     [newData addObject:firstItem]; 
     [firstItem release]; //TODO: Figure out why this is causing EXC_BAD_ACCESS errors 
    } 

    self.hierData = newData; 

上面的代碼在viewcontroller的init方法中。 HierData是一個保留屬性,它在viewControllers dealloc方法中發佈。 GeographyPickerItem保留了兩個字符串,primaryString和subString,並在它們自己的dealloc方法中釋放它們。當瀏覽控制器在導航控制器彈出之後被取消分配時,我的應用程序崩潰(有時)。它崩潰與GeographyPickerItem(無論是在[子釋放]或[primaryString釋放])的dealloc方法一個EXC_BAD_ACCESS信號。

我不明白爲什麼會這樣,因爲我相信我下面正確的內存管理準則。如果我註釋掉firstItem釋放一切都很好。

+0

打開'NSZombie's! –

回答

0

原來,問題很簡單,我叫超級的dealloc在方法的開始而不是結束dealloc方法。在調用[super dealloc]之前,你總是必須釋放實例變量!

1
SomeObject * new_object = [SomeObject alloc] init]; 
self.object = new_object; 
[new_object release]; 

或使用ARC

4

你提到的自動釋放方法是好的,爲的就是與其他常見的成語:

SomeObject *thing = [[SomeObject alloc] init]; 
self.object = thing; 
[thing release]; 

如果你最終overreleasing以後,是你的問題。這部分,你顯然正確地做,不是問題。

0

檢查GeographyPickerItem,如果字符串屬性分配(和更改保留),或檢查你是否總是(發行前)初始化它們。

還記得手動分配的差異:

[[NSString alloc] initWith...] 

必須釋放或自動釋放。

[NSString stringWith...] 

無需釋放。

或使用ARC像meggar說

+0

我無法使用ARC ..希望我能。字符串屬性保留。和我使用[的NSString stringWithString ...]你可以在示例代碼 – FreaknBigPanda

+0

檢查還有什麼地方你釋放firstItem.primaryString和 firstItem.subString看到,因爲該代碼似乎是正確的 –