为什么NSUserDefaults无法保存NSMutableDictionary?

use*_*136 3 iphone xcode nsuserdefaults nsmutabledictionary ios

我想保存NSMutableDictionaryNSUserDefaults.我在stackoverflow中读了很多关于这个主题的帖子......我还发现了一个有效的选项; 然而不幸的是它只工作一次然后它开始只保存(null).有人有提示吗?

谢谢

保存代码:

[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:dictionary] forKey:@"Key"];
[[NSUserDefaults standardUserDefaults] synchronize];
Run Code Online (Sandbox Code Playgroud)

要加载的代码:

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];
NSData *data = [[NSUserDefaults standardUserDefaults]objectForKey:@"Key"];
dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];
Run Code Online (Sandbox Code Playgroud)

将对象添加到的代码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"];
Run Code Online (Sandbox Code Playgroud)

代码到NSLog()值:

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

键也是(null):

NSLog(@"%@"[dictionary allKeys]);
Run Code Online (Sandbox Code Playgroud)

zap*_*aph 10

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

这条线:

dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];
Run Code Online (Sandbox Code Playgroud)

丢弃先前创建的NSMutableDictionary并返回a NSDictionary.

将加载更改为:

NSData *data = [[NSUserDefaults standardUserDefaults]objectForKey:@"Key"];
dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];
Run Code Online (Sandbox Code Playgroud)

完整的例子,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]);
}
Run Code Online (Sandbox Code Playgroud)

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