ios - NSMutableDictionary initWithContentsOfFile 中的内存泄漏

标签 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];
}

根据构建和分析,我在加载自定义项目时存在潜在泄漏

NSMutableDictionary *customItems = [[NSMutableDictionary alloc] initWithContentsOfFile: fullPath];

确实,根据 Instruments 的说法,我的那部分确实有泄漏。但是当我尝试发布或自动发布自定义项目时,我的应用程序崩溃了。即使我将 NSMutableDictionary 更改为 NSDictionary,我仍然存在泄漏。 我该如何解决?

任何帮助将不胜感激。 :)谢谢:)

最佳答案

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

customNames = [[customItems objectForKey: @"customNamesDict"] 保留];

customNamesArray = [[customItems objectForKey: @"customNamesArray"] 保留];

现在您可以发布自定义项目。

关于ios - NSMutableDictionary initWithContentsOfFile 中的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5401586/

相关文章:

string - 为什么简单的 Go 应用程序占用大量内存

c++ - Dr.Memory 发现的错误 : don't know how to fix it

ios - iOS 点缀字体库

ios - Xcode 6.1 中的失败初始值设定项

ios - Storyboard输出与模拟不匹配

objective-c - 在加载 View 之前显示加载指示器

python - 从 SWIG 类型映射中释放内存

c - 什么是 C 中的 pragma align?

c++ - 使用 std::list 和 std::shared_ptr 进行内存管理

c# - 空的 ASP.NET Core (.NET 5.0) 项目对针对其执行的每个请求持续使用更多 RAM