为什么NSUserDefaults无法保存NSMutableDictionary?

3
我将尝试使用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]);

非常好的问题呈现! - zaph
1个回答

10

根据苹果公司关于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输出:
键:Key 2, 值:1
键:Key 1, 值:0
键:Key 4, 值:4
键:Key 3, 值:2


1
新年快乐Zaph: 非常感谢您的帮助。我终于成功让它工作了(通过[NSKeyedArchiver archiveRootObject:counts toFile:path]; /[NSKeyedUnarchiver unarchiveObjectWithFile:path])。 尽管如此,我有一个关于您的答案的问题,因为我无法使用NSUserDefaults使其工作。您建议将加载更改为:NSData *data = [[NSUserDefault standardUserDefaults]objectForKey:@"Key"]; dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];我这样做了,但它不起作用。您是真的这么想还是忘记编辑我的初始输入了? - user1940136
我的回答有些通用,您可以根据自己的情况进行重命名和修复。思路是一旦您可以将其存档为NSData,就可以通过“NSUserDefaults”保存/恢复它。 - zaph

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接