【发布时间】:2014-08-04 19:30:54
【问题描述】:
以下代码在尝试 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];
【问题讨论】:
-
消息说什么?你猜这意味着什么?什么是不可变对象?将 NSDictionary 转换为 NSMutableDictionary 指针会使字典可变吗?
-
我不确定它为什么是 NSDictionary,因为 NSUserDefault 被定义为 NSMutableDictionary - @property (nonatomic, retain) NSMutableDictionary* dictDeviceIp;
-
不知道为什么这个问题被否决了,这解决了我的问题。
-
谢谢鲍勃,人们投反对票的速度太快了,通常在阅读整个问题之前就完成了。无论如何,很高兴看到这篇文章恢复了积极状态!尽管有所有这些反对票,这意味着很多人得到了帮助。
标签: ios objective-c nsuserdefaults nsmutabledictionary mutable