NSString *keyIAmLookingFor = @"work";
NSString *valueIAmLookingFor = @"444-567-9019";
NSArray *addressBookPhoneIndividuals = @[
@{
@"name" : @"Mike Rowe",
@"ID" : @"134",
@"phoneNumbers" : @{
@"work" : @"123-456-8000",
@"school" : @"647-5543",
@"home" : @"123-544-3321",
}
},
@{
@"name" : @"Eric Johnson",
@"ID" : @"1867",
@"phoneNumbers" : @{
@"work" : @"444-567-9019",
@"other" : @"143-555-6655",
}
},
@{
@"name" : @"Robot Nixon",
@"ID" : @"-12",
@"phoneNumbers" : @{
@"work" : @"123-544-3321",
@"school" : @"123-456-8000",
@"home" : @"444-567-9019",
}
},
];
NSString *keyPath = [@"phoneNumbers." stringByAppendingString:keyIAmLookingFor];
NSPredicate *predicate =
[NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:keyPath]
rightExpression:[NSExpression expressionForConstantValue:valueIAmLookingFor]
modifier:NSDirectPredicateModifier
type:NSEqualToPredicateOperatorType
options:0];
NSArray *result = [addressBookPhoneIndividuals filteredArrayUsingPredicate:predicate];
这将返回一个包含“Eric Johnson”字典的数组。
我喜欢NSComparisonPredicate
在进行任何类型的复杂匹配时推荐。查看修饰符、类型和选项的选项。那里有一些很好的内置匹配引擎 - 包括正则表达式和不区分大小写。无论如何,这里可能没有必要,因此您可以替换以下内容:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K = %@", keyPath, valueIAmLookingFor];
如果只关心第一个结果,可以完全跳过 keyPath/predicate 业务:
for (NSDictionary *individualDict in addressBookPhoneIndividuals) {
NSDictionary *phoneNumbers = [individualDict objectForKey:@"phoneNumbers"];
NSString *possibleMatch = [phoneNumbers objectForKey:keyIAmLookingFor];
if ([possibleMatch isEqualToString:valueIAmLookingFor]) {
return individualDict;
}
}
return nil;