Saturday, October 25, 2014

Difference between objectForKey and valueForKey in iOS

You may get this doubt when you work with NSDictionary in iOS. When you use these methods on Dictionaries, there wont be any much difference between objectForKey and valueForKey in iOS. Both methods behaves almost same on dictionaries. But valueForKey used on Key Value Coding (KVC) as its a key value method.

Where to use: objectForKey will work on NSDictionaries and valueForKey will work on NSDictionaries and KVC. On NSDictionaries both returns null if key not found. And valueForKey throws valueForUndefinedKey: exception on KVC if property not found.  Check the examples below for more clarity.

Usage on NSDictionary: We can use objectForKey: and valueForKey:  on dictionaries. Below is the sample code.

    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"king",@"name",@"9985396338",@"phone", nil];
    // using objectForKey method
    NSLog(@"name is %@", [dict objectForKey:@"name"]);
    // displays null as name1 not found in NSDictionary
    NSLog(@"name1 is %@", [dict objectForKey:@"name1"]);

    // using valueForKey method    
    NSLog(@"phone is %@", [dict valueForKey:@"phone"]);
    // displays null as phone1 not found in NSDictionary
    NSLog(@"phone is %@", [dict valueForKey:@"phone1"]);

Usage on KVC: we can't use objectForKey: method on key-value coding. We can use valueForKey: method. Below is the example

// .h file
@interface valueForKeyTest : NSObject
@property NSString *name,*phone;
@end

// .m file
@implementation valueForKeyTest
@synthesize name, phone;
@end

// main.m file
#import "valueForKeyTest.h"
int main(int argc, const char * argv[]) {
    valueForKeyTest *obj = [[valueForKeyTest alloc] init];

    obj.name = @"king";
    obj.phone = @"9985396338";
    
    // valueForKey on accessor methods
    NSLog(@"name is %@", [obj valueForKey:@"name"]);
    NSLog(@"phone is %@", [obj valueForKey:@"phone"]);

    // this will throw valueForUndefinedKey: as name1 is not a property
    NSLog(@"name is %@", [obj valueForKey:@"name1"]);
}



Key Value Coding: A key is unique value, which identifies the property value of the object. A key generally accessor method or instance variable in the object, Check KVC for more info. KVC has below key value methods.


  • setValue:forKey:
  • valueForKey:
  • setValue:forKeyPath:
  • valueForKeyPath: 
  • setValuesForKeysWithDictionary:
  • dictionaryWithValuesForKeys:


Popular Posts