gpt4 book ai didi

ios - NSMutableDictionary initWithContentsOfFile 中的内存泄漏

转载 作者:行者123 更新时间:2023-11-29 05:05:36 33 4
gpt4 key购买 nike

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

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com