NSMutableDictionary: mutating method sent to immutable object

Remixed123 picture Remixed123 · Aug 4, 2014 · Viewed 18.3k times · Source

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;

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

Answer

Catfish_Man picture Catfish_Man · Aug 4, 2014

NSUserDefaults returns immutable objects, even if you put in mutable ones. You must call -mutableCopy on the returned value to get a mutable collection.