NSMutableDictionary:发送到不可变对象的变异方法

Rem*_*123 14 objective-c mutable nsuserdefaults nsmutabledictionary ios

以下代码在尝试removeObjectForKey时返回一个异常,并显示以下错误消息"mutating method sent to immutable object"

NSMutableDictionary * storedIpDictionary = (NSMutableDictionary*)[[NSUserDefaults standardUserDefaults] dictionaryForKey:@"dictDeviceIp"];

NSString *key = self.currentDeviceNameText.text;
NSString *ipAddressTemp = [storedIpDictionary objectForKey:key];

[storedIpDictionary removeObjectForKey:key]; <----Crashes here

storedIpDictionary[key] = ipAddressTemp;
Run Code Online (Sandbox Code Playgroud)

不确定是什么问题,也许是因为从NSUserDefaults检索字典.

但是,以下代码无任何问题.

NSMutableDictionary * storedIpDictionary = (NSMutableDictionary*)[[NSUserDefaults standardUserDefaults] dictionaryForKey:@"dictDeviceIp"];
[storedIpDictionary removeAllObjects];
Run Code Online (Sandbox Code Playgroud)

Cat*_*Man 56

即使你输入了可变对象,NSUserDefaults也会返回不可变对象.您必须在返回的值上调用-mutableCopy以获取可变集合.


Rem*_*123 3

这是最终起作用的代码,我使用了上面其他人提供的一些细节,但没有人对其进行完全解释。

- (void)cleanDictionary
{
    NSMutableDictionary * storedIpDictionary = [[[NSUserDefaults standardUserDefaults] objectForKey: @"dictDeviceIp"] mutableCopy];

    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"dictDeviceIp"];

    NSString *oldKey = self.currentDeviceNameText.text;
    NSString *newKey = self.deviceNameChangeText.text;
    NSString *ipAddressTemp = [storedIpDictionary objectForKey:oldKey];

    // Make some change to the structure
    [storedIpDictionary removeObjectForKey:oldKey];  // Remove object
    storedIpDictionary[newKey] = ipAddressTemp;      // Add object with new key

    // Add it the whole thing back into NSUserDefaults
    [[NSUserDefaults standardUserDefaults] setObject:storedIpDictionary forKey:@"dictDeviceIp"];

    // Synchronize to ensure it's saved
    [[NSUserDefaults standardUserDefaults] synchronize];
}
Run Code Online (Sandbox Code Playgroud)