NSMutableDictionary:发送到不可变对象的变异方法 [英] NSMutableDictionary: mutating method sent to immutable object

查看:106
本文介绍了NSMutableDictionary:发送到不可变对象的变异方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The following code is returning an exception with the following error message "mutating method sent to immutable object" when attempting to removeObjectForKey

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;

不确定是什么问题,可能是因为从NSUserDefaults检索字典。

Not sure what the issue is, perhaps it is due to retrieving the dictionary from a NSUserDefaults.

但是下面的代码没有任何问题。

However the following code works without any issues.

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


推荐答案

这是最终有效的代码,我用了一些从上面的其他人提供的细节,但没有完全解释。

This is the code that eventually worked, I used some of the details provided from others above, but none had it completely explained.

- (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];
}

这篇关于NSMutableDictionary:发送到不可变对象的变异方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆