搜索字典数组的简便方法

时间:2014-02-10 21:56:36

标签: ios iphone objective-c ipad

我有一个NSArray看起来像:

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

我想获取lastName = XYZ的字典元素,即数组元素:

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

有没有一个简单的方法来获得它没有很多循环?感谢。

1 个答案:

答案 0 :(得分: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);
}