2

我有一个名为的数组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:以使其通过嵌套数组进行搜索。

4

1 回答 1

11

“艺术家”是一个数组,因此您必须在谓词中使用“ANY”:

[NSPredicate predicateWithFormat:@"ANY %K.%K CONTAINS[c] %@",
              @"artist",@"name",searchText];

请注意,您可以使用“复合谓词”,而不是手动构建搜索结果的“联合”:

NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:
                          @[predicateEventsByName, predicateEventsByArtistName]];
self.filteredEventsArray = [self.eventsArray filteredArrayUsingPredicate:predicate];
于 2013-08-14T19:23:02.397 回答