【问题标题】:How to add string and key to dictionary in iPhone programmatically?如何以编程方式将字符串和键添加到 iPhone 中的字典?
【发布时间】:2012-10-31 06:41:49
【问题描述】:

我使用以下代码将值写入字典,但是当将新值添加到字典时它不会更新,它只会显示只有最近添加的值的 plist,它也崩溃了。

nameString=nameTxt.text;
NSFileManager *mngr=[NSFileManager defaultManager];
NSArray *docDir=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath=[docDir objectAtIndex:0];
NSString *filePath=[docPath stringByAppendingPathComponent:@"score.plist"];
NSString *bundlePath=[[NSBundle mainBundle] pathForResource:@"score" ofType:@"plist"];

if ([mngr fileExistsAtPath:filePath]) {
    NSLog(@"File exists");
}
else {      
    NSLog(@"NO file exists");
    [[NSFileManager defaultManager] copyItemAtPath:bundlePath toPath:filePath error:NULL];      
}   

dict=[[NSMutableDictionary alloc]init];
dict=[NSMutableDictionary dictionaryWithContentsOfFile:filePath];
NSLog(@"dict is %@",dict);
[dict setObject:nameString forKey:@"100"];
[dict writeToFile:filePath atomically:YES];

[dict release];

当我使用最后一行“[dict release]”时出现崩溃 我的包中有一个 score.plist 文件。

【问题讨论】:

  • 在你的代码中删除这段代码 dict=[[NSMutableDictionary alloc]init];[dict release];,它会起作用

标签: iphone xcode plist


【解决方案1】:

崩溃是因为这条线,

dict=[[NSMutableDictionary alloc]init];
dict=[NSMutableDictionary dictionaryWithContentsOfFile:filePath];

您分配内存的第一行,然后覆盖 dict 参数以链接到不属于您的静态字典。所以旧的被泄露了,当你释放它时,它会尝试释放静态的。

而不是那种用途,

dict=[NSMutableDictionary dictionaryWithContentsOfFile:filePath];

并且不要使用发布声明。既然你不拥有它,你不必释放它。

Check this

【讨论】:

  • dict=[[NSMutableDictionary alloc]init];create newNSMutableDictionary, dict=[NSMutableDictionary dictionaryWithContentsOfFile:filePath];只从文件路径复制字典,不会覆盖字典
  • 它将覆盖第一个分配的字典。检查developer.apple.com/library/mac/#documentation/cocoa/conceptual/…
  • dict 存储文件中的数据,dict 在全局中声明
  • 我没明白你的意思。确实,它正在从文件中读取。之后读取的字典归操作系统所有,我们分配给 dict ,这使得它泄漏分配的 dict 对象。因此,当我们发布它时,它会崩溃。请阅读苹果文档以更好地理解这个概念。
【解决方案2】:

这是一个简单的记忆问题。除了解决问题,你还必须了解问题。

dict 是您在全局范围内声明的 NSMutableDictionary。这样你就可以分配它来使用它,这样你就不会失去字典的范围。

所以一开始说 'ViewDidLoad:' ,你可以把它分配和初始化为

dict=[[NSMutableDictionary alloc]init];

或者在目前的情况下你可以像这样使用

dict=[[NSMutableDictionary alloc]initWithContentsOfFile: filePath];

这样您就可以使用score.plist 文件分配字典,一切都会正常工作。

在您的情况下发生的事情是您分配了dict。但是在下一行中,您将 dict 的分配对象替换为语句

中的 autoreleaed 对象
dict=[NSMutableDictionary dictionaryWithContentsOfFile:filePath];

由于类方法总是返回自动释放的对象,当你尝试释放自动释放的对象时,它会崩溃。 :-)

希望你明白了。

现在的解决方案是你可以换行

dict=[[NSMutableDictionary alloc]init];

dict=[[NSMutableDictionary alloc]initWithContentsOfFile: filePath];

并删除该行

dict=[NSMutableDictionary dictionaryWithContentsOfFile:filePath];

一切都会奏效。快乐编码。 :-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    相关资源
    最近更新 更多