NSMutableDictionary: mutating method sent to immutable object

前端 未结 6 2133
栀梦
栀梦 2021-01-11 10:24

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



        
6条回答
  •  执笔经年
    2021-01-11 11:09

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

提交回复
热议问题