ios – NSMutableDictionary:mutate方法发送到不可变对象

前端之家收集整理的这篇文章主要介绍了ios – NSMutableDictionary:mutate方法发送到不可变对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下代码在尝试删除ObjectForKey时返回异常,并显示以下错误消息“mutate 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];

解决方法

NSUserDefaults返回不可变对象,即使你插入了可变对象.您必须在返回的值上调用-mutableCopy以获取可变集合.
原文链接:https://www.f2er.com/iOS/337530.html

猜你在找的iOS相关文章