我正在尝试保存一个NSMutableDictionary
with 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]);