NSMutableArray initWithContentsOfFile内存泄漏

时间:2010-01-18 19:59:02

标签: cocoa memory nsmutablearray memory-leaks

我是iPhone开发的新手,我有这个内存泄漏。

我使用NSMutableArray来检索位于Documents目录中的.plist文件的内容。

我第一次使用它时,一切都很顺利,但是如果我多次调用它会导致内存泄漏。

这是我的代码:

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  NSArray *paths = NSSearchPathForDirectoriesInDomains
                       (NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentsDirectory = [paths objectAtIndex:0];
     //make a file name to write the data to using the
     //documents directory:
  fullFileName = [NSString stringWithFormat:@"%@/SavedArray", documentsDirectory];
     //retrieve your array by using initWithContentsOfFile while passing
     //the name of the file where you saved the array contents.
  savedArray = nil;
  savedArray = [[NSMutableArray alloc] initWithContentsOfFile:fullFileName];
  self.composedArray = [savedArray copy];
  [savedArray release];
  [self.tableView reloadData];
}

每次视图消失时我都会发布它

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];
  [composedArray release];
  composedArray = nil;
  [savedArray release];
}

我正在使用Instruments,这告诉我内存泄漏源是这行代码:

savedArray = [[NSMutableArray alloc] initWithContentsOfFile:fullFileName];

我不知道如何解决这个漏洞,如果有人可以分享任何解决方案,我会非常感激。

提前致谢。

1 个答案:

答案 0 :(得分:5)

财产声明如何composedArray

如果声明是:

@property(retain) id composedArray;

这就是内存泄漏的地方。 copy会增加引用计数,retain也会增加。如果您分配到composedArray的任何时候,您将分配一份副本(通过阅读您的代码),您应该将您的财产声明为:

@property(copy) id composedArray;

然后更改您的代码:

self.composedArray = savedArray;

(副本将在合成访问者中发生。)

相关问题