Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data NSPredicate with to-Many Relationship

I have two Entities in CoreData called User and Coupon, they are in Many-to-Many relationship. I wanted to fetch for all Coupons except those owned by user.userId = 1, where userId is NSString.

I used: [NSPredicate predicateWithFormat:@"NOT(ANY couponOwners.userId = %@)", @"4"]; to be the predicate of my fetchedResultsController

but not filtering with correct results. One of the User in couponOwners of the Coupon is still having userId = 4.

Could somebody please help? I have been stuck for quite a while. Thanks in advance.

like image 941
John Avatar asked Mar 30 '13 20:03

John


People also ask

How do I create one-to-many relationships in core data?

Let's finish with a look at one-to-many relationships. Open Core_Data.xcdatamodeld, select the Person entity, and create a relationship named children. Set the destination to Person, set the type to To Many, and leave the inverse relationship empty for now.

How does core data handle inverse relationships?

Core Data creates this relationship for us. If a relationship has an inverse relationship, then Core Data takes care of this automatically. You can verify this by asking newAddress for its persons. Updating a relationship isn't difficult either.

Should core data be sorted or unsorted?

Most people new to Core Data expect a sorted array, but Core Data returns a set, which is unsorted. Working with sets has its advantages as you'll learn later. Enough with the theory, open the project from the previous article or clone it from GitHub.

How do I update the relationship between two mutable set values?

We do this by invoking mutableSetValueForKey (_:) on newPerson and adding otherAddress to the mutable set. There is no need to tell Core Data that we've updated the relationship. Core Data keeps track of the mutable set that it gave us and updates the relationship.


1 Answers

Core Data predicates with "NOT ANY" do not work (that seem to be a Core Data bug). Actually

[NSPredicate predicateWithFormat:@"NOT(ANY couponOwners.userId = %@)", @"4"];

returns the same result set as

[NSPredicate predicateWithFormat:@"ANY couponOwners.userId != %@", @"4"];

which is of course wrong. As a workaround, you can use a SUBQUERY:

[NSPredicate predicateWithFormat:@"SUBQUERY(couponOwners, $c, $c.userId == %@).@count == 0", @"4"]
like image 109
Martin R Avatar answered Sep 30 '22 12:09

Martin R