2010-10-05 109 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