我有一个数组,其中包含几个带有键的NSDictionaries:
> NSString *名称
> NSString * ID
> NSDictionary * phoneNumbersDict
现在我想过滤这个数组,找到一个具有phoneNumbersDict键@“keyIAmLookingFor”和值@“valueIAmLookingFor”的数组.
NSMutableArray *addressBookPhoneIndividuals = [NSMutableArray array]; for (int i = 0; i < x; i++) { [addressBookPhoneIndividuals addObject:@{ @"name" : @"...",@"ID" : @"...",@"phoneNumbers" : @{...} }]; }
解决方法
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 /谓词业务:
for (NSDictionary *individualDict in addressBookPhoneIndividuals) { NSDictionary *phoneNumbers = [individualDict objectForKey:@"phoneNumbers"]; NSString *possibleMatch = [phoneNumbers objectForKey:keyIAmLookingFor]; if ([possibleMatch isEqualToString:valueIAmLookingFor]) { return individualDict; } } return nil;