views:

4293

answers:

3

What is the difference between objectForKey and valueForKey? I looked both up in the documentation and they seemed the same to me.

+4  A: 

This mailing list discussion provides some relevant answers.

Nathan de Vries
+1  A: 

When you do valueForKey: you need to give it an NSString, whereas objectForKey: can take any NSObject subclass as a key. This is because for Key-Value Coding, the keys are always strings.

In fact, the documentation states that even when you give valueForKey: an NSString, it will invoke objectForKey: anyway unless the string starts with an @, in which case it invokes [super valueForKey:], which may call valueForUndefinedKey: which may raise an exception.

dreamlax
+17  A: 

"objectForKey:" is an NSDictionary method. An NSDictionary is a collection class similar to an NSArray, except instead of using indexes, it uses keys to differentiate between items. A key is an arbitrary string you provide. No 2 objects can have the same key (just as no 2 objects in an NSArray can have the same index).

"valueForKey: is KVC method. It works with ANY class. "valueForKey" allows you to access an instance variable using a string. So for instance, if I have an Account class with an instance variable accountNumber, I can do the following:

NSNumber *anAccountNumber = [NSNumber numberWithInt:12345];

Account *newAccount = [[Account alloc] init];
[newAccount setAccountNumber:anAccountNUmber];

NSNumber *anotherAccountNumber = [newAccount accountNumber];

Using KVC, I can also do it like this:

NSNumber *anAccountNumber = [NSNumber numberWithInt:12345];

Account *newAccount = [[Account alloc] init];
[newAccount setValue:anAccountNumber forKey:@"accountNumber"];

NSNumber *anotherAccountNumber = [newAccount valueForKey:@"accountNumber"];

Those are equivalent sets of statements.

I know you're thinking: wow, but sarcastically. KVC doesn't look all that useful. In fact, it looks "wordy". But when you want to change things at runtime, you can do lots of cool things that are much more difficult in other languages (but this is beyond the scope of your question).

If you want to learn more about KVC, there are many tutorials if you Google especially at Scott Stevenson's blog.

Hope that helps.

Corey Floyd
valueForKey behaves differently for NSDictionary objects depending on whether the key starts with an @ symbol.
dreamlax
objectForKey: accepts any object as a key, not just strings. The only requirement is that the key support the NSCopying protocol.
Ashley Clark
Both of these points are definitely true. NSDictionaries are a special case and you don't have to use strings for keys. I didn't really go into subtleties of either as it seems that the asker just required a simplistic comparison.
Corey Floyd