Jon*_*han 2 memory cocoa memory-leaks nsmutablearray
我是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];
}
Run Code Online (Sandbox Code Playgroud)
每次视图消失时我都会释放它
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[composedArray release];
composedArray = nil;
[savedArray release];
}
Run Code Online (Sandbox Code Playgroud)
我正在使用Instruments,这告诉我内存泄漏源是这行代码:
savedArray = [[NSMutableArray alloc] initWithContentsOfFile:fullFileName];
Run Code Online (Sandbox Code Playgroud)
我不知道如何解决这个漏洞,如果有人可以分享任何解决方案,我会非常感激.
提前致谢.
财产的声明如何composedArray
?
如果声明是:
@property(retain) id composedArray;
Run Code Online (Sandbox Code Playgroud)
这就是内存泄漏的地方.copy
增加引用计数,同样如此retain
.如果您分配给composedArray
您的任何时候将分配一份副本(通过阅读您的代码),您应该将您的财产声明为:
@property(copy) id composedArray;
Run Code Online (Sandbox Code Playgroud)
然后更改您的代码:
self.composedArray = savedArray;
Run Code Online (Sandbox Code Playgroud)
(副本将在synthethised访问器中发生).