Утечка памяти в NSMutableDictionary initWithContentsOfFile - PullRequest
0 голосов
/ 23 марта 2011

Это мой код: (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, у меня есть потенциальная утечка в загрузке пользовательских элементов

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

достаточно верно, в соответствии с документами, у меня есть утечка в этой части. Но когда я попытался выпустить или автоматически выпустить customItems, мое приложение вылетает. Даже если я изменю NSMutableDictionary на NSDictionary, у меня все еще есть утечка. Как это исправить?

Любая помощь будет принята с благодарностью. :) Спасибо:)

Ответы [ 2 ]

1 голос
/ 23 марта 2011

Вам необходимо сохранить customNames и customNamesArray, поскольку вы используете ссылку из словаря customItems и после передачи ссылки вы ее освобождаете.

customNames = [[customItems objectForKey: @ "customNamesDict"] retain];

customNamesArray = [[customItems objectForKey: @ "customNamesArray"] retain];

Теперь вы можете выпускать customItems.

0 голосов
/ 23 марта 2011

Ваш код правильный, как я вижу. Вы можете увидеть ответ здесь и, возможно, это поможет - Проблема утечки с initWithContentsOfFile

У меня только один вопрос: вы создаете NSString * fullPath и никогда не выпускаете его. Это автоматически выпущенная строка? Если так - ваш код в порядке.

...