我有一个 Group 实体,其中包含许多 Item 实体。一个项目实体可以属于多个组。我的模型的相关部分如下所示:
问题
当我打电话时
[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/