【问题标题】:Why does NSUserDefaults fail to save NSMutableDictionary?为什么 NSUserDefaults 无法保存 NSMutableDictionary?
【发布时间】:2012-12-31 19:31:04
【问题描述】:

我正在尝试用NSUserDefaults 保存NSMutableDictionary。我在 stackoverflow 中阅读了许多关于该主题的帖子......我还找到了一个可行的选项;然而不幸的是它只工作了一次,然后它开始只保存(null)。 有人有提示吗?

谢谢

要保存的代码:

[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:dictionary] forKey:@"Key"];
[[NSUserDefaults standardUserDefaults] synchronize];

要加载的代码:

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];
NSData *data = [[NSUserDefaults standardUserDefaults]objectForKey:@"Key"];
dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];

将对象添加到NSMutableDictionary的代码:

[dictionary setObject:[NSNumber numberWithInt:0] forKey:@"Key 1"];
[dictionary setObject:[NSNumber numberWithInt:1] forKey:@"Key 2"];
[dictionary setObject:[NSNumber numberWithInt:2] forKey:@"Key 3"];

NSLog() 值的代码:

for (NSString * key in [dictionary allKeys]) {
    NSLog(@"key: %@, value: %i", key, [[dictionary objectForKey:key]integerValue]);
}

而且键是(null):

NSLog(@"%@"[dictionary allKeys]);

【问题讨论】:

  • 非常好的问题!

标签: iphone ios xcode nsuserdefaults nsmutabledictionary


【解决方案1】:

来自 Apple 的 NSUserDefaults objectForKey 文档:
返回的对象是不可变的,即使您最初设置的值是可变的。

行:

dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];

丢弃之前创建的NSMutableDictionary 并返回NSDictionary

将加载改为:

NSData *data = [[NSUserDefaults standardUserDefaults]objectForKey:@"Key"];
dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];

完整的例子,在这个例子中也不需要使用NSKeyedArchiver

NSDictionary *firstDictionary = @{@"Key 4":@4};
[[NSUserDefaults standardUserDefaults] setObject:firstDictionary forKey:@"Key"];

NSMutableDictionary *dictionary = [[[NSUserDefaults standardUserDefaults] objectForKey:@"Key"] mutableCopy];

dictionary[@"Key 1"] = @0;
dictionary[@"Key 2"] = @1;
dictionary[@"Key 3"] = @2;

for (NSString * key in [dictionary allKeys]) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

NSLog 输出:
键:键 2,值:1
键:键 1,值:0
键:键 4,值:4
键:键 3,值:2

【讨论】:

  • 新年快乐 Zaph:非常感谢您的帮助。我终于成功地使它工作(通过 [NSKeyedArchiver archiveRootObject:counts toFile:path]; /[NSKeyedUnarchiver unarchiveObjectWithFile:path])。尽管如此,我对您的回答有疑问,因为我无法使其与 NSUserDefaults 一起使用。您建议将加载更改为: NSData *data = [[NSUserDefault standardUserDefaults]objectForKey:@"Key"];字典 = [NSKeyedUnarchiver unarchiveObjectWithData:data];我这样做了,但它不起作用。您真的是这个意思还是忘记编辑我的初始输入?
  • 我的回答有点笼统,重命名并根据您的情况进行修复。这个想法是,一旦您可以存档到 NSData,您就可以通过NSUserDefaults 保存/恢复某些内容。
猜你喜欢
  • 2010-10-03
  • 2011-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多