问题描述
在查看文档时,我几乎看不到任何重大差异。 value和object都是id 类型,因此可以是任何对象。 Key一次是字符串,另一种情况是id。其中一个似乎保留了对象,而另一个则没有。还有什么?哪一个适用于哪种情况?
When looking at the documentation, I hardly see any big difference. Both "value" and "object" are of type id, so can be any object. Key is once a string, and in the other case an id. One of them seems to retain the object, and the other don't. What else? Which one is for what case?
推荐答案
setValue:forKey:
is 协议的一部分,除此之外,还允许您从Interface Builder等访问对象属性。 setValue:forKey:
在 NSDictionary
以外的类中实现。
setValue:forKey:
is part of the NSKeyValueCoding protocol, which among other things, lets you access object properties from the likes of Interface Builder. setValue:forKey:
is implemented in classes other than NSDictionary
.
setObject:forKey:
是 NSMutableDictionary的
存在的原因。它的签名恰好与setValue:forKey:非常相似,但更通用(例如任何键类型)。签名非常相似,这有点巧合。
setObject:forKey:
is NSMutableDictionary's
reason to exist. Its signature happens to be quite similar to setValue:forKey:, but is more generic (e.g. any key type). It's somewhat of a coincidence that the signatures are so similar.
令人困惑的是,NSMutableDictionary的 setValue:forKey:$的实现在大多数情况下,c $ c>相当于
setObject:forKey:
。在其他类中, setValue:forKey:
更改成员变量。在 NSMutableDictionary
中,它会更改字典条目,除非您在键前加上@字符 - 在这种情况下它会修改成员变量。
What adds to the confusion is that NSMutableDictionary's implementation of setValue:forKey:
is equivalent to setObject:forKey:
in most cases. In other classes, setValue:forKey:
changes member variables. In NSMutableDictionary
, it changes dictionary entries, unless you prefix the key with a '@' character -- in which case it modifies member variables.
因此,简而言之,当您需要使用字典键和值时,使用 setObject:forKey:
,并且 setValue:forKey:
在极少数情况下你需要解决。
So, in a nutshell, use setObject:forKey:
when you need to work with dictionary keys and values, and setValue:forKey:
in the rarer cases where you need to tackle KVP.
编辑:哦,看起来这个问题已被问及之前回答:
and oh, it looks like this has been asked and answered before: Difference between objectForKey and valueForKey?
这篇关于setObject:forKey:和setValue:forKey:在NSMutableDictionary中的区别在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!