问题描述
我有一个数组,其中包含几个 NSDictionaries ,它们的键为:
I have an array which consists of several NSDictionaries with the keys:
-
NSString *名称
-
NSString * ID
-
NSDictionary * phoneNumbersDict
NSString *name
NSString *ID
NSDictionary *phoneNumbersDict
现在我要过滤此数组以找到一个具有 phoneNumbersDict
键 @ keyIAmLookingFor
和值 @ valueIAmLookingFor
。
Now I want to filter this array to find the one which has the phoneNumbersDict
key @"keyIAmLookingFor"
and the value @"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];
这将返回包含埃里克·约翰逊字典的数组。
This will return an array containing the "Eric Johnson" dictionary.
在进行任何类型的复杂匹配时,我建议使用 NSComparisonPredicate
。查看修饰符,类型和选项的选项。那里有一些内置的匹配引擎,包括正则表达式和不区分大小写。无论如何,这里可能没有必要,所以您可以替换以下内容:
I like to recommend NSComparisonPredicate
when doing any kind of complex matching. Look at the options for modifier, type and options. There are some good built in matching engines in there - including regular expressions and case insensitivity. Anyway, it probably isn't necessary here, so you could substitute the following:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K = %@", keyPath, valueIAmLookingFor];
如果只关心第一个结果,则可以完全跳过keyPath /谓词业务:
If you only care about the first result, you can skip the keyPath/predicate business altogether:
for (NSDictionary *individualDict in addressBookPhoneIndividuals) {
NSDictionary *phoneNumbers = [individualDict objectForKey:@"phoneNumbers"];
NSString *possibleMatch = [phoneNumbers objectForKey:keyIAmLookingFor];
if ([possibleMatch isEqualToString:valueIAmLookingFor]) {
return individualDict;
}
}
return nil;
这篇关于如何过滤NSDictionary和NSDictionary的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!