Thursday, May 9, 2013

NSDictionary valueForKey example ios


valueForKey:

Returns the value associated with a given key.
- (id)valueForKey:(NSString *)key
Parameters
key
The key for which to return the corresponding value. Note that when using key-value coding, the key must be a string (see “Key-Value Coding Fundamentals”).
Return Value
The value associated with key.
Discussion of [NSDictionary valueForKey]
If key does not start with “@”, invokes objectForKey:. If key does start with “@”, strips the “@” and invokes [super valueForKey:] with the rest of the key.
Example of [NSDictionary valueForKey]
NSString *value = [dictionary valueForKey:@"myKey"];
if (!value) value = @"defaultValue";
[myObject setMyString:value];
Example of [NSDictionary valueForKey]
NSDictionary *answer = [self.answers objectAtIndex:indexPath.row];
if ([answer respondsToSelector:@selector(objectForKey)]) {
    cell.textLabel.text = [answer valueForKey:@"answer_id"];
} else {
    [NSException raise:@"Answer is of invalid class" format:@"It should be able to respond to valueForKey, class: %@", [answer class]];
}
Example of [NSDictionary valueForKey]
id answer = [self.answers objectAtIndex:indexPath.row];
if (answer isKindOfClass:[NSDictionary class])
{
  cell.textLabel.text = [answer valueForKey:@"answer_id"];
    } else {
        // I'm ending up here, instead of the cell.textLabel being set
        [NSException raise:@"Answer is of invalid class" format:@"It should be able to respond to valueForKey, class: %@", [answer class]];
    }