2010-10-05 119 views
0

我正指着行「NSDictionary *dw = [NSDictionary dictionaryWithContentsOfFile:path];」內存泄漏使用下面的代碼的NSDictionary財產

NSDictionary *_allData; 

@property (nonatomic, retain) NSDictionary *allData; 

@synthesize allData = _allData; 

+ (NSString*)getNSPath 

{ 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

NSString *documentsDirectory = [paths objectAtIndex:0]; 

NSString *path = [documentsDirectory stringByAppendingPathComponent:@"alarm.plist"]; 

return path; 
} 


- (NSDictionary *)allData 
{ 
NSString *path = [saveAlarm getNSPath]; 
NSDictionary *dw = [NSDictionary dictionaryWithContentsOfFile:path]; 


_allData = [NSDictionary dictionaryWithDictionary:dw]; 

    return _allData; 
} 

的數據在plist中不斷變化的,當我問要檢索的是新出現的財產則泄漏。 任何建議如何清楚?或者如何實現這種沒有泄漏的事情?

謝謝

回答

2

您需要在重新分配_allData之前釋放它。您還需要在分配時保留它。

編輯:納入羅伯特的改進,擺脫不需要的NSDictionary。

EDIT2:由於您要通過API邊界返回對象,因此需要將其重新調整爲自動釋放對象。

- (NSDictionary *)allData 
{ 
    NSString *path = [saveAlarm getNSPath]; 
    [_allData release]; 
    _allData = [[NSDictionary dictionaryWithContentsOfFile:path] retain]; 

    return [_allData autorelease]; 
} 

您發佈的代碼是一個有點奇怪的,你會創建一個名爲ALLDATA屬性,告訴它使用_allData爲伊娃(用@synthesize),然後執行該設置伊娃定製吸氣。如果將該屬性聲明爲只讀屬性,則可以刪除@synthesize語句。

如果你只在這個方法內部使用_allData而不是這個類中的其他地方,你可以完全擺脫它。這裏有一個是做同樣的事情更簡單的版本:

- (NSDictionary *)allData 
{ 
    NSString *path = [saveAlarm getNSPath]; 
    return [NSDictionary dictionaryWithContentsOfFile:path]; 
} 
+0

此解決方案在添加了保留的行上使內存泄漏864字節。不知道爲什麼我應該保留它,當它是類方法。 – Vanya 2010-10-05 10:41:07

+0

啊。當你通過API邊界返回一個對象時,你需要將它作爲自動發佈來返回。我會更新代碼。 – 2010-10-05 10:43:17

+0

您需要保留它,因爲您正在將它存儲在ivar中。否則,該對象將被釋放,而你的伊娃仍然有一個引用它。 – 2010-10-05 10:49:27

0

你爲什麼不更換

NSDictionary *dw = [NSDictionary dictionaryWithContentsOfFile:path]; 


_allData = [NSDictionary dictionaryWithDictionary:dw]; 

隨着

_allData = [NSDictionary dictionaryWithContentsOfFile:path]; 

那麼你不必擔心DW NSDictionary的autorelease可能導致你的泄漏。

+0

這是一個很好的建議,因爲它的代碼少得多,並且不會創建額外的字典,但仍然會泄漏。泄漏是因爲您將一個新的NSDictionary分配給_allData,而沒有先釋放現有的值。 – 2010-10-05 10:26:32

+0

這個解決方案在開始時不會泄漏,但當我要求檢索新值時會發生泄漏(32字節)......所以目前還沒有進展 – Vanya 2010-10-05 10:43:32