Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving an NSManagedObject from an NSSet

I've got two entities with a one-to-many relationship between them. The entity that holds "many" has the expected NSSet property. What I'm not sure is how to access a specific element in the NSSet. The NSSet contains objects that have several properties, one of which is currentWeek. I want to access an object within my NSSet that has a specific currentWeek.

I know I can do a FetchRequest to find it, but I assume there is a more straightforward way using the NSSet.

like image 639
Chris Roberts Avatar asked Dec 28 '22 01:12

Chris Roberts


1 Answers

You have a couple options.

NSArray* objectsArray = [yourSet allObjects];

This will populate objectsArray with all the objects in the set, at which point you can enumerate through them looking for the object or objects you want.

You could also use a predicate something like this:

NSPredicate *desiredWeekPredicate = [NSPredicate predicateWithFormat:@"currentWeek == %d", currentWeekYouWant];
NSSet *objectsWithDesiredWeek = [yourSet filteredSetUsingPredicate:predicate];

(Your predicate will look different depending on how you store currentWeek). If you only have one object per currentWeek, you can just call -anyObject on the objectsWithDesiredWeek set to get your object. If you can have more than one object with the same currentWeek then the calling the -allObjects method on objectsWithDesiredWeek will get you an array with all the objects that use your desired week.

like image 85
Simon Goldeen Avatar answered Feb 08 '23 20:02

Simon Goldeen