3

我正在尝试保存一个NSMutableDictionarywith NSUserDefaults。我在 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]);
}

而且键是(空):

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

1 回答 1

10

来自 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 输出:
key:Key 2,value:1
key:Key 1,value:0
key:Key 4,value:4
key:Key 3,value:2

于 2012-12-31T19:35:47.540 回答