代码之家  ›  专栏  ›  技术社区  ›  David Weiss

如何使用NSFetchedResultsController设置NSPredicate以筛选指定组中的项

  •  5
  • David Weiss  · 技术社区  · 14 年前

    我有一个组实体,其中有许多项目实体。一个项目实体可以在多个组中。我的模型的相关部分如下所示:

    alt text

    当我打电话的时候

    [fetchedResultsController performFetch:&error]
    

    *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'to-many key not allowed here' ***
    

    [NSPredicate predicateWithFormat:@"groups == %@", self.group];
    

    但我不知道我做错了什么。我已经阅读了NSPredicate文档并尝试了以下方法:

    [NSPredicate predicateWithFormat:@"ANY groups IN %@", [NSArray arrayWithObject:self.group]];
    [NSPredicate predicateWithFormat:@"ANY groups LIKE %@", self.group];
    [NSPredicate predicateWithFormat:@"ANY groups == %@", self.group];
    [NSPredicate predicateWithFormat:@"ANY groups IN %@", [NSArray arrayWithObject:self.group]];
    [NSPredicate predicateWithFormat:@"groups == %@", self.group];
    

    我有一个NSFetchedResultsController,我正试图将其配置为仅显示特定组中的项。设置NSFetchedResultsController的代码如下所示:

    // create the fetch request
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    
    // configure the entity
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];
    
    // configure the predicate
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"groups == %@", self.group];
    [fetchRequest setPredicate:predicate];
    
    // configure the sort descriptors
    NSSortDescriptor *indexSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"uniqueID" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObject:indexSortDescriptor];
    [fetchRequest setSortDescriptors:sortDescriptors];
    
    // create the fetched results controller
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"ItemsCache"];
    
    // configure the fetched results controller 
    aFetchedResultsController.delegate = self;
    
    2 回复  |  直到 7 年前
        1
  •  6
  •   Marcus S. Zarra    14 年前

    如果没有代码,很难做到100%,但您应该能够:

    [NSPredicate predicateWithFormat:@"%@ in groups", [self group]];
    

        2
  •  1
  •   TechZen    14 年前

    你倒过来了。因为你似乎已经拥有了团队(我猜 self.group 是一个 Group 对象),您应该使用self.group.items向self.group请求其项目。一旦你有了 Item 与特定对象相关的对象 对象,然后您可以根据需要对它们进行排序以供显示。