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
  • 615
  • 3
  • 8
  • 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,316
  • 6
  • 48
  • 60
rob mayoff
  • 375,296
  • 67
  • 796
  • 848