0

I have a NSArray looking like:

 [{@"firstName":@"abc", @"lastName":@"ABC"},
   ...
  {@"firstName":@"xyz", @"lastName":@"XYZ"}]

I want to get the dictionary element in which lastName=XYZ, that is, the array element:

  {@"firstName":@"xyz", @"lastName":@"XYZ"}

is there an easy way to get it without a lot of loops? Thanks.

user2543991
  • 595
  • 3
  • 7
  • 16

1 Answers1

1
NSArray *people = ...;
NSUInteger chosenIndex = [people indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
    NSDictionary *person = obj;
    return [person[@"lastName"] isEqualToString:@"XYZ"];
}];
if (chosenIndex != NSNotFound) {
    NSDictionary *chosenPerson = people[chosenIndex];
    NSLog(@"I chose %@", chosenPerson);
}
hgwhittle
  • 9,146
  • 6
  • 47
  • 60
rob mayoff
  • 358,182
  • 62
  • 756
  • 811