Let's have that in a context:
There are different ways to access an object that is accessable by a key.
A. Key-Value Coding
Key-value coding is done with -valueForKey:
et al. Since this is implemented in NSObject
nearly all objects having properties (have properties accessible by key) response to this. Basically this methods forms a selector from the key and sends it to the object. Beside this you have the ability to build key path and there are some special keys, i. e. count.
This is completely implemented outside the compiler.
Instances of NSDictionary
supports this.
B. Subscripting
[]
is the syntax for subscripting. If the key between [
and ]
is an object, it is keyed subscripting. The compiler transforms that syntax into a -objectForKeyedSubscript:
et al. message. The receiver has to implement the methods.
Instances of NSDictionary
supports this by simply sending -objectForKey:
et al. to self
. But there is a little difference, see below.
C. NSDictionary
Additionally NSDictionary
implements -objectForKey:
.
There is no right or wrong. Personally I would prefer the most specific message for instances of NSDictionary
, -objectForKey:
et al. However, keyed subscription might be better readable.
Key-value coding is good, if you do not know the type of the receiver.
BTW: Key-value coding and keyed subscripting let's you set nil values in an instance of NSMutableDictionary
, while -setObject:forKey:
et al. forbids that.