155

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?

4

4 回答 4

165

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: 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.

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.

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.

EDIT: and oh, it looks like this has been asked and answered before: Difference between objectForKey and valueForKey?

于 2009-08-08T19:09:45.047 回答
86

另一个区别是,如果您给 一个 nil 值setValue:forKey:,它会从字典中删除该键(如果存在),否则什么也不做。但是如果你给 一个 nil 值setObject:forKey:,它会引发一个异常。

于 2011-02-16T02:21:46.387 回答
11

-setValue:forKey:只需发送-setObject:forKey:给接收者,除非值为nil,在这种情况下发送-removeObjectForKey

死的简单。

于 2016-09-02T09:55:06.577 回答
4

anObject — 键的值。该对象在添加到NSDictionary. 该值不能为零。

aKey — 值的键。复制密钥(使用copyWithZone:; 密钥必须符合NSCopying协议)。键不能为零。

value — 键的值。

key — 价值的关键。请注意,使用键值编码时,键必须是字符串(请参阅“键值编码基础”)。

于 2011-02-17T12:00:10.457 回答