0
votes

I have a data structure in Core Data like so...

User

Item

Category

User has a toMany relationship "FavouriteItems" to the Item entity. Category also has a toMany relationship "Items" to the Item entity.

The user can select favourite items from any categories they wish. At the moment I am listing all the items and then displaying the Category alongside.

What I'd like to do is display all the user's favouriteItems for a selected Category.

i.e. select all the Items that have a relationship with Category x and User y.

I'm currently doing this by getting all the Items through one relationship (i.e. User.favouriteItems) and then filtering the NSSet using a block predicate.

Is it possible though to do this with a simple CoreData predicate?

Hmm... thinking about it would a predicate like this work...

[NSPredicate predicateWithFormat:@"interestedUser.id = %@ AND category.id = %@", user.id, category.id];

And then run a fetch request on the item entity?

Would that work?

1
Quick update. It doesn't like the to-many relationship used in the predicate. - Fogmeister

1 Answers

1
votes

Shooting pretty blind as that's an awkward scenario to set up just to answer a question but perhaps

If you are filtering an array of Items which has the correct inverse relationships set up.

[NSPredicate predicateWithFormat:@"%@ IN interestedUsers AND %@ IN categories", 
                                 someUser, 
                                 someCategory];

Basically the Item has many users (interestedUsers) so we are saying is our user in this collection.

Similarly the Item has many categories (categories) so we are saying AND is our chosen category in this collection.