Where's the difference between setObject:forKey: and setValue:forKey: in NSMutableDictionary?
صفحه اصلي

Where's the difference between setObject:forKey: and setValue:forKey: in NSMutableDictionary?



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?


What is better: Global string or singleton?

1:

How do I launch my settings bundle from my application?
setValue:forKey: is part of the NSKeyValueCoding protocol, which among another things, lets you access object properties from the likes of Interface Builder. Long-term potential of iPhone/Windows Mobile development platformssetValue:forKey: is implemented in classes another than NSDictionary.. How combine TabBar + Navigation with XCode setObject:forKey: is NSMutableDictionary's reason to exist. Best way to manage probably huge photo library with iPhone SDKIts signature happens to be quite similar to setValue:forKey:, although is more generic (e.g. How make scrolling function with Interface builder on the iPhone?any key type). How programatically move a UIScrollView to focus in a control above keyboard?It's any what of a coincidence this the signatures are so similar.. How much of a transition is programming Java to iPhone apps? What adds to the confusion is this NSMutableDictionary's implementation of setValue:forKey: is equivalent to setObject:forKey: in most cases. In another 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 job 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?.

2:

Ananother difference is this if you commit a nil value to setValue:forKey:, it removes the key from the dictionary if it exists, otherwise does nothing. But if you commit a nil value to setObject:forKey:, it raises an exception..

3:

anObject — The value for key. The object receives a retain message before being added to the NSDictionary. This value need not be nil.. aKey — The key for value. The key is copied (using copyWithZone:; keys need conform to the NSCopying protocol). The key need not be nil.. value — The value for key.. key — The key for value. Note this when using key-value coding, the key need be a string (see “Key-Value Coding Fundamentals”)..

4:

-setValue:forKey: just send -setObject:forKey: to the receiver, unless the value is nil, in which case send -removeObjectForKey.. Dead simple..


78 out of 100 based on 18 user ratings 658 reviews

*