【问题标题】:How do I set up an NSPredicate that filters for items in a specified group using NSFetchedResultsController如何使用 NSFetchedResultsController 设置过滤指定组中项目的 NSPredicate
【发布时间】:2010-08-05 20:05:05
【问题描述】:

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

问题

当我打电话时

[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;

【问题讨论】:

  • 我曾经通过打破另一个实体的关系来处理多对多关系。可能是以下问题显示了我是如何做到的。 stackoverflow.com/questions/2822625/… 您还可以使用数据模型编辑器中的谓词编辑器来构造谓词。希望对你有帮助,
  • 关于谓词编辑器的提醒很有帮助。我还没弄明白,谢谢!

标签: iphone cocoa-touch core-data


【解决方案1】:

没有代码可以玩,很难做到 100%,但你应该能够:

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

这是假设您的 fetch 正在尝试拉回 Item 实体。

【讨论】:

  • 太棒了!就是这样!谢谢马库斯。现在我看到了,这很有意义。
【解决方案2】:

你倒退了。由于您似乎已经拥有该组(我假设 self.groupGroupobject),您应该使用 self.group.items 向 self.group 询问其项目。一旦您拥有与特定 Group 对象相关的 Item 对象,您就可以根据需要对它们进行排序以进行显示。

【讨论】:

  • 我明白了,如果我在 Mac 上,这正是我会做的,但我在 iPhone 上,NSFetchedResultsController 在那里提供了一些真正的优势,所以我想用它。这是问题的核心:如何使用 NSFetchedResultsController 给定这个模型设置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多