iphone - 如何设置一个 NSPredicate 来使用 NSFetchedResultsController 过滤指定组中的项目

标签 iphone cocoa-touch core-data

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

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;

最佳答案

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

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

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

关于iphone - 如何设置一个 NSPredicate 来使用 NSFetchedResultsController 过滤指定组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3418721/

相关文章:

ios - 如何测量兆字节数据量?

ios - 何时布局 UIView Controllers View 的 subview ?

ios - 在 CoreData 之外使用自动生成的模型文件对象

core-data - NSPredicate 中使用的 SUBQUERY( ) 是否不支持所有集合运算符,如@max、@min?

ios - 核心数据 - 关系查询

ios - iphone X 最大加速度计和陀螺仪频率

ios - 按下另一个 View Controller 时, Root View Controller 的 View 消失

iphone - iPhone中使用NSData的内存泄漏问题

ios - Xcode 8.1 IOS10.1 CoreData删除并没有真正删除

iphone - 检测 UIView 子类中的自转