以下代码在尝试移除 ObjectForKey 时返回异常,并显示以下错误消息“将方法发送到不可变对象(immutable对象)”
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];
最佳答案
NSUserDefaults 返回不可变对象(immutable对象),即使你放入可变对象。您必须对返回值调用 -mutableCopy 以获得可变集合。
关于ios - NSMutableDictionary:发送到不可变对象(immutable对象)的变异方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25126148/