这是我的代码:(customNames和customNamesArray是静态变量)
-(void) loadCustomDataFromDisk
{
NSString *fullPath = [self filePathAndFileName: @"customData.plist"];
if ( ![[NSFileManager defaultManager] fileExistsAtPath: fullPath] )
{
NSLog(@"Loading file fails: File not exist");
customNames = [[NSMutableDictionary alloc] init];
customNamesArray = [[NSMutableArray alloc] init];
}
else
{
NSMutableDictionary *customItems = [[NSMutableDictionary alloc] initWithContentsOfFile: fullPath];
customNames = [customItems objectForKey: @"customNamesDict"];
customNamesArray = [customItems objectForKey: @"customNamesArray"];
if (!customItems)
NSLog(@"Error loading file");
[customItems release];
}
}
-(void) saveCustomDataToDisk
{
NSString *path = [self filePathAndFileName: @"customData.plist"];
NSMutableDictionary *customItems = [[NSMutableDictionary alloc] init];
[customItems setObject: customNames forKey: @"customNamesDict"];
[customItems setObject: customNamesArray forKey: @"customNamesArray"];
BOOL success;
success = [customItems writeToFile:path atomically:YES];
if (!success)
NSLog(@"Error writing file: customDataDict.plist");
[customItems release];
}
根据Build and Analyze的说法,我在加载customItems时有潜在的泄漏
NSMutableDictionary *customItems = [[NSMutableDictionary alloc] initWithContentsOfFile: fullPath];
根据Instruments的说法,这确实是正确的,但我确实在该部分存在泄漏。但是,当我尝试发布或自动释放customItems时,我的应用程序崩溃了。即使我将NSMutableDictionary更改为NSDictionary,也仍然存在泄漏。
我该如何解决?
任何帮助将不胜感激。 :) 谢谢 :)
最佳答案
您必须保留customNames和customNamesArray,因为您使用的是字典customItems中的引用,并且在传递引用后将其释放。
customNames = [[customItems objectForKey:@“ customNamesDict”]保留];
customNamesArray = [[customItems objectForKey:@“ customNamesArray”]保留];
现在,您可以释放customItems。
关于ios - NSMutableDictionary initWithContentsOfFile中的内存泄漏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5401586/