NSMutableDictionary中的内存泄漏initWithContentsOfFile

时间:2011-03-23 06:28:03

标签: ios memory-management memory-leaks nsmutabledictionary

这是我的代码:(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];

根据乐器的说法,我确实有泄漏。但是当我尝试发布或自动释放customItems时,我的应用程序崩溃了。即使我将NSMutableDictionary更改为NSDictionary,我仍然有泄漏。 我该如何解决?

非常感谢任何帮助。 :)谢谢:)

2 个答案:

答案 0 :(得分:1)

您必须保留customNames和customNamesArray,因为您正在使用字典customItems中的引用,并且在传递引用之后您将释放它。

customNames = [[customItems objectForKey:@“customNamesDict”] retain];

customNamesArray = [[customItems objectForKey:@“customNamesArray”] retain];

现在您可以发布customItems。

答案 1 :(得分:0)

我的代码是正确的。你可以在这里看到答案,可能有帮助 - Leak problem with initWithContentsOfFile

我只有一个问题:您创建NSString * fullPath并且永远不会释放它。它是自动释放的字符串吗?如果是这样 - 你的代码很好。