NSFetchRequest,按对象ID过滤

时间:2012-03-22 09:23:34

标签: objective-c ios core-data

我正在使用以下代码从核心数据图表中获取数据:

- (void)setupFetchedResultsController
{
    // 1 - Decide what Entity you want
    NSString *entityName = @"Snag"; // 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:@"project.id = %@", projectPassedToController.id];

    // 4 - Sort it if you want
    request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"dateTaken"
                                                                                     ascending:YES
                                                                                      selector:@selector(localizedCaseInsensitiveCompare:)]];
    // 5 - Fetch it
    self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                        managedObjectContext:self.managedObjectContext
                                                                          sectionNameKeyPath:nil
                                                                                   cacheName:nil];

但是,我只想返回与传递给此View Controller的项目具有相同唯一标识符的项目(使用ProjectPassedToController变量)

我不想按project.name过滤,因为该字段可由用户编辑。我需要按项目的唯一标识符进行过滤,但我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

通过过滤项目与人之间的关系来解决这个问题。

 request.predicate = [NSPredicate predicateWithFormat:@"belongsToProject = %@", _selectedProject];