Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coredata fetch predicate for NSSet

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?

like image 239
Subhash Avatar asked Dec 08 '22 06:12

Subhash


1 Answers

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"]
like image 82
Martin R Avatar answered Dec 22 '22 11:12

Martin R