我有一个名为的数组self.eventsArray
,如下所示:
[
{
"artist": [
{
"artist_name": "Dillon Francis",
"name": "Dillon Francis",
},
{
"artist_name": "Major Lazer",
"name": "Major Lazer",
},
{
"artist_name": "Flosstradamus ",
"name": "Flosstradamus",
}
],
"name": "Mad Decent Block Party NYC",
},
{
"artist": [
{
"artist_name": "Ryan Raddon",
"name": "Kaskade",
}
],
"name": "Kaskade Atmosphere Tour NYC",
},
]
我一直试图通过使用NSPredicate
两次来过滤它。当用户搜索时,需要按名称(在艺术家数组中)或名称(在顶级数组中)进行过滤。
NSPredicate *predicateEventsByName = [NSPredicate predicateWithFormat:@"SELF.%K contains[c] %@",@"name",searchText];
NSPredicate *predicateEventsByArtistName = [NSPredicate predicateWithFormat:@"SELF.%K.%K contains[c] %@",@"artist",@"name",searchText];
NSMutableArray *unfilteredEventsArray = [[NSMutableArray alloc] initWithCapacity:0];
unfilteredEventsArray = [NSMutableArray arrayWithArray:[self.eventsArray filteredArrayUsingPredicate:predicateEventsByName]];
[unfilteredEventsArray addObjectsFromArray:[self.eventsArray filteredArrayUsingPredicate:predicateEventsByArtistName]];
[self.filteredEventsArray addObjectsFromArray:[[NSSet setWithArray:unfilteredEventsArray] allObjects]];
使用此代码,self.filteredEventsArray
将填充与顶级匹配的任何搜索词"name"
。它不会为嵌套的艺术家提供任何搜索结果"name"
。我怀疑它不会搜索嵌套数组的原因是因为这一行:
NSPredicate *predicateEventsByArtistName = [NSPredicate predicateWithFormat:@"SELF.%K.%K contains[c] %@",@"artist",@"name",searchText];
但我不知道如何更改它predicateWithFormat:
以使其通过嵌套数组进行搜索。