问题
A
.b
and B
.a
are inverse to-many relationships. Why does this predicate for A
work:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT SELF IN %@", bObject.a];
while this one does not:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT %@ IN b", bObject];
I think both predicates should give the same result — the collection of A
s that have no relation with bObject
via a<-->b
. But in fact, the first one gives the correct collection while the second one not.
Update:
Here is a sample project wherein A
.b
is embodied by Account
.filtered_clients
and B
.a
is embodied by Client
.filtered_by
.
Toggle commenting of line 143 and line 144 in MasterViewController.m
to see the difference.
Please help me either find the bug in my code, or confirm it is a Core Data
bug so I can report it to Apple. Thanks very much.
回答1:
Here is another idea: maybe it is trying to "negate" the bObject
with the NOT
. Thus, try:
@"NOT (%@ IN b)"
回答2:
From the documentation:
Important You must define many-to-many relationships in both directions—that is, you must specify two relationships, each being the inverse of the other. You can’t just define a to-many relationship in one direction and try to use it as a many-to-many. If you do, you will end up with referential integrity problems.
So check this:
- A has a to many relationship to B.
- B has a to many relationship to A.
- The A relationship is the inverse of the B relationship.
- The B relationship is the inverse of the A relationship.
回答3:
I think I found the answer for people coming across this question. Apparently you do need to use SELF for it to work, at least in my case with two to-many relations. This works for me:
NOT (SELF IN %@)
来源:https://stackoverflow.com/questions/9065711/why-not-in-does-not-work-in-this-nspredicate