Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate find object with attribute in NSSet

I have an NSMangedObject that contains NSSet of other NSManagedObjects.

I need to check if these objects has an value in NSSet and then return them.

I use MagicalRecord for fetching data.

So I need something like this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"stringObjects contains %@", string];

So if NSSet stringObjects contains some string that I am looking for so then return object I have requested.

One note here: stringObjects (name just for example it represent my NSSet) it is NSSet that contains NSManagedObjects, so I need to search them by some id (for example string_id attribute).

So then model looks like this

NSSet *set = MainObject.stringObjects;
NSString *string_id_for_first_object = [[[set allObjects] objectAtIndex:0] string_id];

Just for better understanding relationship.

But the question is about how can I create predicate to check if NSSet contains needed id.

like image 281
Matrosov Oleksandr Avatar asked Nov 11 '13 11:11

Matrosov Oleksandr


1 Answers

If I understand your question correctly, stringObjects is a to-many relationship from one entity A to another entity B, and B has an attribute string_id.

To find all A objects that are related to any B object with the given string id, use:

NSString *stringId = …; // The string that you are looking for
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY stringObjects.string_id == %@", stringId];
like image 188
Martin R Avatar answered Oct 23 '22 10:10

Martin R