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

本文是小编为大家收集整理的关于NSMutableDictionary: 发送给不可变对象的变异方法的处理方法,想解了NSMutableDictionary: 发送给不可变对象的变异方法的问题怎么解决?NSMutableDictionary: 发送给不可变对象的变异方法问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

以下代码在尝试 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;

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

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

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

推荐答案

这是最终成功的代码,我使用了上面其他人提供的一些细节,但没有一个完整的解释.

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

本文地址:https://www.itbaoku.cn/post/924716.html