Why does NSUserDefaults fail to save NSMutableDictionary?

后端 未结 1 748
慢半拍i
慢半拍i 2021-01-06 11:59

I’m trying to save a NSMutableDictionary with NSUserDefaults. I read many posts on the topic in stackoverflow... I also found one option that worke

相关标签:
1条回答
  • 2021-01-06 12:14

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

    The line:

    dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    

    discards the previously created NSMutableDictionary and returns a NSDictionary.

    Change the loading to:

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

    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 output:
    key: Key 2, value: 1
    key: Key 1, value: 0
    key: Key 4, value: 4
    key: Key 3, value: 2

    0 讨论(0)
提交回复
热议问题