键值编码 - setValue:forKey: 其中值为 NULL
我正在阅读的文档说 setValue:forKey:
会将 NULL
值视为被删除。然而,我有一个如下所示的始终崩溃的示例:
[myObj setValue:[aDictionary valueForKey:@"keyDoesNotExist"] forKey:@"anotherKey"];
如果 < code>aDictionary 不包含键 keyDoesNotExist
。有什么办法解决这个问题吗?在这里做什么合适?
myObj 是 NSManagedObject 的一个实例。 “anotherKey”是一对多关系,其中 myObj 可以包含许多“anotherKey”。
I am reading documentation that says setValue:forKey:
will treat a NULL
value as if it is being removed. Yet, I have an example such as the following that is consistently crashing:
[myObj setValue:[aDictionary valueForKey:@"keyDoesNotExist"] forKey:@"anotherKey"];
This line of code crashes if aDictionary
does not contain the key keyDoesNotExist
. Is there any way around that? What's the appropriate thing to do here?
myObj is an instance of NSManagedObject
. "anotherKey" is a one to many relationship where myObj can contain many of "anotherKey".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您使用 nil 值调用
setValue:forKey:
时,将调用方法-setNilValueForKey:
。默认情况下(在 NSObject 的实现中),这会引发无效参数异常。您可以通过覆盖-setNilValueForKey:
并执行您想要的任何操作来使用 nil 值执行其他操作。或者,如果您直接调用 myObj 的 anotherKey setter,则不应出现异常(当然取决于
setAnotherKey:
的实现):您正在阅读的文档可能是针对 NSMutableDictionary 的。如果值为 nil,NSMutableDictionary 的
setValue:forKey:
实现会调用removeObjectForKey:
。对于 NSObject 子类来说并非如此,我认为 myObj 就是这样。此行为在 NSKeyValueCoding 协议参考文档。
When you call
setValue:forKey:
with a nil value, the method-setNilValueForKey:
is called. By default (in NSObject's implementation), this raises an invalid argument exception. You can do something else with a nil value by overriding-setNilValueForKey:
and doing whatever you'd like.Alternatively, if you call myObj's anotherKey setter directly, you shouldn't get an exception (dependent on the implementation of
setAnotherKey:
of course):The documentation you're reading is probably for NSMutableDictionary. NSMutableDictionary's implementation of
setValue:forKey:
callsremoveObjectForKey:
if the value is nil. That's not true for NSObject subclasses, which I'm presuming is what myObj is.This behavior is discussed in the NSKeyValueCoding Protocol Reference documentation.