NSPredicate find object with attribute in NSSet

2019-03-26 16:50发布

问题:

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.

回答1:

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];