Thursday, May 9, 2013

NSDictionary objectForKey example ios


objectForKey:

Returns the value associated with a given key.
- (id)objectForKey:(id)aKey
Parameters
aKey
The key for which to return the corresponding value.
Return Value
The value associated with aKey, or nil if no value is associated with aKey.
Example of [NSDictionary objectForKey]
int code = [[NSDictionary objectForKey:@"code"]intValue];
Example of [NSDictionary objectForKey]
NSNumber *code = [myDict objectForKey:@"code"];
NSInteger codeInteger = [code integerValue];
Example of [NSDictionary objectForKey]
NSArray *results = [feed objectForKey:@"results"];
NSDictionary *firstResult = [results objectAtIndex:0];
NSArray *addressComponents = [firstResult objectForKey:@"address_components"];
NSDictionary *firstAddress = [addressComponents objectAtIndex:0];
NSString *longName = [firstAddress objectForKey:@"long_name"];
Example of [NSDictionary objectForKey]
NSDictionary *someDictionary;

// create someDictionary, populate it, for example (note: we assume photoOfKeys.jpg
// definitely exists, not a good idea for production code — if it doesn't we'll get
// a nil there and anything after it won't be added to the dictionary as it'll appear
// that we terminated the list):
someDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                @"hat", @"favouriteGarment",
                                [UIImage imageNamed:@"photoOfKeys.jpg"], @"@allKeys",
                                [NSArray array], [NSNumber numberWithInt:2],
                                nil];

NSObject *allKeys; // we make no assumptions about which type @allKeys will be,
                   // but are going to assume we can NSLog it, so it needs to be
                   // a descendant of NSObject rather than 'id' so as to definitely
                   // respond to the 'description' message — actually this is just
                   // compile time semantics, but if someone else reads this code it'll
                   // make it obvious to them what we were thinking...

// some code to get all of the keys stored in the dictionary and print them out;
// should print an array containing the strings 'favouriteGarment', '@allKeys' and
// the number 2
allKeys = [someDictionary valueForKey:@"@allKeys"];
NSLog(@"%@", allKeys);

// some code to get the object named '@allKeys' from the dictionary; will print
// a description of the image created by loading photoOfKeys.jpg, above
allKeys = [someDictionary objectForKey:@"@allKeys"];
NSLog(@"%@", allKeys);