NSPredicate with a!=?

我有核心数据实体人员和边界。 他们有多对多的关系(每个人可以有很多边界,每个边界可以有很多人)。

我正在尝试创建一个列表,列出了Fred Fred没有关系的界限。

Person *person = [Person MR_findFirstByAttribute:@"name" withValue:@"Fred"]; DLog(@"person.boundaries.count: %d", person.boundaries.count); NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY persons != %@", person]; DLog(@"testBoundaries.count: %d", [Boundary MR_countOfEntitiesWithPredicate:predicate]); 

我在数据库中有47个边界,Fred可以看到所有47个。所以我希望我的fetch返回0:

 DEBUG | -[LoginViewController viewDidLoad] | person.boundaries.count: 47 DEBUG | -[LoginViewController viewDidLoad] | testBoundaries.count: 47 

我的谓词出了什么问题?

 [NSPredicate predicateWithFormat:@"ANY persons != %@", fred] 

找到与Fred之外的任何人相关的所有对象。 你想要的是什么

 [NSPredicate predicateWithFormat:@"NOT(ANY persons = %@)", fred] 

应该返回与Fred无关的所有对象。

但是 ,似乎存在一个Core Data错误,“NOT ANY”或“NONE”在谓词中无法正常工作,将NSPredicate Aggregate Operations与NONE进行比较。 解决方法是使用SUBQUERY:

 [NSPredicate predicateWithFormat:@"SUBQUERY(persons, $p, $p == %@).@count == 0", fred] 

如果有一个叫Fred的人有边界,你需要先在Class Boundary询问。 它应该是这样的:

 NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Boundary"]; fetchRequest.predicate = [NSPredicate predicateWithFormat:@"ANY persons.name != %@", person.name]; 

这将获取Fred没有的所有边界。