开发者

Retrieving an NSManagedObject from an NSSet

开发者 https://www.devze.com 2023-02-10 09:49 出处:网络
I\'ve got two entities with a one-to-many relationship between them. The e开发者_开发百科ntity that holds \"many\" has the expected NSSet property. What I\'m not sure is how to access a specific eleme

I've got two entities with a one-to-many relationship between them. The e开发者_开发百科ntity 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号