这是一个简单的问题,但是我找不到答案。
我正在构建一个用于存储Projects和People上的数据的应用程序,该数据使用Core Data存储在SQLite数据库中。
一个项目可以有很多人,但是一个人只能分配到一个项目。我在表视图中显示数据,此视图现在每当您查看任何项目时都显示存储在数据库中的所有人员-这并不理想。
我只想展示那些参与该项目的人。我将如何以编程方式进行此操作?这是使用过滤完成的吗?例如:
- (void)setupFetchedResultsController
{
// 1 - Decide what Entity you want
NSString *entityName = @"People"; // Put your entity name here
NSLog(@"Setting up a Fetched Results Controller for the Entity named %@", entityName);
// 2 - Request that Entity
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
// 3 - Filter it if you want
//request.predicate = [NSPredicate predicateWithFormat:@"people.name = someones name"];
// 4 - Sort it if you want
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"lastName"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)]];
// 5 - Fetch it
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
[self performFetch];
}
最佳答案
您需要一个谓词,充当过滤器。请参阅NSPredicate上的文档。
谓词必须引用您感兴趣的项目。从所显示的少量代码中,您可以尝试类似的事情(具体取决于您自己的实现)。
request.predicate = [NSPredicate predicateWithFormat:@"people.project = %@", projectName"];