如何通过嵌套数组来预测键
我有一个名为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
来过滤它。 用户search时,需要按名称(在艺术家数组中)或名称(在顶级数组中)进行过滤。
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"
search词。 它不会给出嵌套艺术家"name"
任何search结果。 我怀疑为什么它不会search嵌套数组是因为这一行:
NSPredicate *predicateEventsByArtistName = [NSPredicate predicateWithFormat:@"SELF.%K.%K contains[c] %@",@"artist",@"name",searchText];
但我不知道如何改变predicateWithFormat:
使其通过嵌套数组进行search。
“artist”是一个数组,所以你必须在谓词中使用“ANY”
[NSPredicate predicateWithFormat:@"ANY %K.%K CONTAINS[c] %@", @"artist",@"name",searchText];
请注意,不是手动build立search结果的“联合”,而是使用“复合谓词”:
NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates: @[predicateEventsByName, predicateEventsByArtistName]]; self.filteredEventsArray = [self.eventsArray filteredArrayUsingPredicate:predicate];