【问题标题】:iOS Dictionary causes memory leakiOS 字典导致内存泄漏
【发布时间】:2012-08-30 14:22:28
【问题描述】:

为什么字典的以下实现会导致内存泄漏?请参阅下面的屏幕截图。几乎所有的泄漏都来自这种方法。

- (void) setLocation:(NSString *) location:(NSString *) turnPage {
    NSLog(@"Start setLocation");
    //---get the path to the property list file---
    NSString *localPlistFileNameConf = [[self documentsPath] stringByAppendingPathComponent:@"Config.plist"];
    NSMutableDictionary *copyOfDict;
    //---if the property list file can be found---
    if ([[NSFileManager defaultManager] fileExistsAtPath:localPlistFileNameConf]) {
        //---load the content of the property list file into a NSDictionary object---
        NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:localPlistFileNameConf];
        //---make a mutable copy of the dictionary object---
        copyOfDict = [dict mutableCopy];
        [dict release];
    }
    else {
        //---load the property list from the Resources folder---
        NSString *pListPath = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"];
        NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:pListPath];
        //---make a mutable copy of the dictionary object---
        copyOfDict = [dict mutableCopy];
        [dict release];
    }
    location = [self checkLocationValidity:location:turnPage];
    [copyOfDict setValue:location forKey:@"Location"];
    [self writeConfigToFile:copyOfDict];
    NSLog(@"End setLocation");
}

【问题讨论】:

  • 在方法末尾添加[copyOfDict release];mutableCopy 使用保留计数 = 1 创建它。

标签: ios memory-leaks


【解决方案1】:

你不会在任何地方发布copyOfDict。您拥有使用以copy 开头的方法创建的任何对象,因此您需要释放这些对象。出于效率原因,由于NSDictionary 类集群中的一些技巧,它可能会将源错误地报告为原始字典。尝试对您的代码运行分析,它应该会向您指出这些事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 2013-11-30
    • 2015-07-06
    • 2014-06-07
    • 2013-11-20
    • 2011-10-28
    相关资源
    最近更新 更多