Coredata fetch predicate for NSSet
Asked Answered
B

1

5

I have a ManagedPhoto coredata object that contains a NSSet attribute called tags. Each object in the tags set is a NSString.

I need to fetch all ManagedPhoto objects that have tags with a specific value, say 'party'. This is what I'm doing -

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"ManagedPhoto"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"SELF.tags == 'party'"];
NSArray *results = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];

But I always get an empty results array even though I know for sure that there are ManagedPhotos with tags containing 'party'. I've tried this as well -

fetchRequest.predicate = [NSPredicate predicateWithFormat:@"SELF.tags IN %@", @[@"party"]];

I've tried many other things as well but nothing has worked so far! Any thought?

Boorman answered 21/8, 2014 at 20:55 Comment(2)
Is tags just a set of strings, or is it a relationship to another entity having a string property?Nickelous
tags is just a set of stringsBoorman
N
16

To fetch objects that have at least one tag with the specified value, the following predicate should work

[NSPredicate predicateWithFormat:@"ANY tags == 'party'"]

or better

[NSPredicate predicateWithFormat:@"ANY tags == %@", @"party"]

But I assume that the set is defined as a transformable property, which means that it is stored as a binary archive in the SQLite file. Then the above queries will work at most for objects already loaded into the managed object context, but not against the store file.

You probably should define tags as a to-many relationship to another entity which has a String property (e.g. "name") and then query with the predicate

[NSPredicate predicateWithFormat:@"ANY tags.name == %@", @"party"]
Nickelous answered 21/8, 2014 at 21:2 Comment(3)
Yes, the set is stored as a transformable property! And its makes sense now why it isn't working. How should I be storing the set? Thxs.Boorman
@user1656412: As a relationship, as I tried to explain in the last part of the answer.Nickelous
Got it! I'll try that out. Thxs again!Boorman

© 2022 - 2024 — McMap. All rights reserved.