CoreData:NSFetchedResultsController一对多到多对多的关系

时间:2015-06-02 00:01:05

标签: ios objective-c core-data nspredicate

我在app上工作的是我使用核心数据,核心数据对象如下所示:

enter image description here 提供theaterName和genreName我想显示actorsName。有人知道建立NSPredicate的方法吗?

1 个答案:

答案 0 :(得分:2)

您可以使用SUBQUERY来构建深入“到很多”关系的NSPredicates:

    // Set predicate
NSPredicate *requestPredicate = [NSPredicate predicateWithFormat:@"SUBQUERY(genres, $g, ANY $g.movies.name == %@).@count != 0",  @"Batman vs Superman"];
[fetchRequest setPredicate:requestPredicate];

<强>更新

根据您更新的示例,您需要嵌套的子查询,如下所示:

 NSPredicate *requestPredicate = [NSPredicate predicateWithFormat:@"SUBQUERY(movies, $m, ANY $m.genres.name == %@).@count != 0 AND SUBQUERY(movies, $m, SUBQUERY($m.genres, $g, ANY $g.theaters.name == %@).@count != 0).@count != 0", @"Action", @"Harkins"];

以下是Cast实体提取示例:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Cast" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
NSArray *sortDescriptors = @[sortDescriptor];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
// Set predicate
NSPredicate *requestPredicate = [NSPredicate predicateWithFormat:@"SUBQUERY(movies, $m, ANY $m.genres.name == %@).@count != 0 AND SUBQUERY(movies, $m, SUBQUERY($m.genres, $g, ANY $g.theaters.name == %@).@count != 0).@count != 0", @"Action", @"Harkins"];
[fetchRequest setPredicate:requestPredicate];
// Fetch
NSError *error = nil;
if (![aFetchedResultsController performFetch:&error]) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
// Check fetched objects
NSArray *fetchedObjects = [aFetchedResultsController fetchedObjects];
for (Cast *eachCast in fetchedObjects) {
    NSLog(@"Each Cast name: %@", eachCast.name);
}

只需用所需的流派名称替换@“Action”,用剧院名称替换@“Harkins”。

以下是我设置核心数据模型的方法: Core data model setup