NSPredicate find object with attribute in NSSet
Asked Answered
B

1

8

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.

Blatman answered 11/11, 2013 at 11:43 Comment(1)
a set has no order so the FIRST object is actually ANYONEWittenberg
S
17

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];
Schram answered 11/11, 2013 at 11:51 Comment(3)
Is there any option after doing like you described, then to extend the predicate to return only objects from B that match that criteria ? In other words I would like after getting all A's that have stringObjects.string_id == %@, the reference to stringObjects have only results from B in set - that have string_id == %@. Because after such type of fetch, you will get all A's correctly but when manipulating with A.stringObjects you will always get all B's that relate to A and not only the ones having string_id == %@ from main fetch. Thank youGurrola
@cybercow: No, that is not possible. A fetch request cannot return "modified" objects. - If you need something like this then you probably better fetch the B objects with the given string_id directly.Schram
Thank you very much for your answer, i ended up using predicate search on B's NSSet directly after initial fetch request on A and is working fine.Gurrola

© 2022 - 2024 — McMap. All rights reserved.