Thursday, May 3, 2018

valueForKey (vs) objectForKey

We frequently use valueForKey, setValueForKey and objectForkey. setObjectForKey when using Dictionaries. In this post, Let’s see the use cases of those and the difference b/w them.

objectForKey takes any object(id) as key value.
valueForKey takes only NSString as key value.

If we pass other than string to valueForKey, It gives a warning and at runtime app crashes.


setValueForKey takes value as any object(id) and key as only NSString.

setObjectForKey takes object as any object(id) and key as any object which confirms to NSCopying protocol.

valueForKey and setValueForKey are intended for KVC.

Hope this post is useful. Feel free to comment incase of any queries.