CoreData :NSFetchedResultsController 一对多对多的关系

CoreData :NSFetchedResultsController one to many to many to many relationship

我在开发应用程序时使用了核心数据,核心数据对象如下所示:

提供 theaterName 和 genreName 我想显示 actorsName。有人知道构建 NSPredicate 的方法吗?

您可以使用 SUBQUERY 构建深入 "to many" 关系的 NSPredicate:

    // 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" 替换为剧院名称即可。

以下是我设置核心数据模型的方式: