我有以下格式的一系列词典
[
{
"student": {
"id": "1",
"studentUserDetail": {
"firstName": "Bonny",
"lastName": "Roby"
}
}
},
{
"student": {
"id": "1",
"studentUserDetail": {
"firstName": "Bonny",
"lastName": "Kety"
}
}
},
{
"student": {
"id": "1",
"studentUserDetail": {
"firstName": "Arther",
"lastName": "Fone"
}
}
},
]
在上面的数组中,我需要在内部键student.StudentUserDetails.firstName中过滤包含serachKey(例如Bonny)的所有元素。如何使用NSPredicate
进行过滤答案 0 :(得分:5)
NSString *name = @"Bonny";
NSPredicate *pred = [NSPredicate predicateWithFormat:
@"student.studentUserDetail.firstName == %@", name];
NSArray *arr = [self.anArray filteredArrayUsingPredicate:pred];
NSLog(@"Bonny found at : %@", arr);
编辑:
如果要根据模式进行搜索,请使用:
NSPredicate *pred = [NSPredicate predicateWithFormat:
@"student.studentUserDetail.firstName beginswith[cd] %@", name];
答案 1 :(得分:2)
NSArray *array = @[
@{
@"student": @{
@"id": @"1",
@"studentUserDetail": @{
@"firstName": @"Bonny",
@"lastName": @"Roby"
}
}
},
@{@"student": @{
@"id": @"1",
@"studentUserDetail": @{
@"firstName": @"Bonny",
@"lastName": @"Kety"
}
}
},
@{
@"student": @{@"id": @"1",
@"studentUserDetail": @{
@"firstName": @"Arther",
@"lastName": @"Fone"
}
}
}];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(student.studentUserDetail.firstName) == %@", @"Bonny"];
NSArray *newArray = [array filteredArrayUsingPredicate:predicate];
答案 2 :(得分:0)
NSPredicate *filter = [NSPredicate predicateWithFormat:@"student.studentUserDetail.firstName CONTAINS[cd] %@ ", searchString];
对我来说很完美