且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么NSUserDefaults无法保存NSMutableDictionary?

更新时间:2021-06-30 22:54:01

来自Apple的 NSUserDefaults文档objectForKey

返回的对象是不可变的,即使您最初设置的值是可变的。

From Apple's documentation for NSUserDefaults objectForKey:
The returned object is immutable, even if the value you originally set was mutable.

该行:

dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];

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

discards the previously created NSMutableDictionary and returns a NSDictionary.

将加载更改为:

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

完整的例子,也没有必要使用 NSKeyedArchiver 在此示例中:

Complete example, there is also no need to use NSKeyedArchiver in this example:

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

NSLog output:
key: Key 2, value: 1
key: Key 1, value: 0
key: Key 4, value: 4
key: Key 3, value: 2