2011-03-23 32 views
0

这是我的代码:(customNames和customNamesArray是静态变量)内存泄漏的NSMutableDictionary initWithContentsOfFile

-(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]; 
} 

根据建立和分析,我在装载customItems

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

真正潜在的泄漏根据仪器,足够的,我确实有泄漏的部分。但是,当我尝试释放或autoreleasing customItems,我的应用程序崩溃。即使我将NSMutableDictionary更改为NSDictionary,我仍然有泄漏。 我该如何解决这个问题?

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

+0

很难看出你的代码有什么问题。你能证明你是否释放它?你显然需要释放它,但是它却知道为什么它没有看到更多的代码而崩溃。 – shannoga 2011-03-23 07:00:15

+0

嗨,我编辑原帖以添加更多代码:)感谢您的回复。 – purplelilgirl 2011-03-23 07:20:48

回答

1

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

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

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

现在您可以释放customItems。

+0

工作:)谢谢:) – purplelilgirl 2011-03-24 07:07:05

0

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

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