开发者

How do I query/filter a to-many relationship in Core Data

I have Customer, Event and Address objects in my data model. Both Customer and Address have a one-to-many relationship to Event.

I can get the distinct list of addresses for a开发者_运维技巧 customer's events for by doing this:

NSSet *addressSet = [customer valueForKeyPath:@"events.address"];

For the part of the UI I'm working on now, I need to display the address from the most recent event prior to now that has an address.

I'm starting to go down the path of creating a NSFetchRequest, setting it's entity, sort descriptors, predicate and then looping through the results, but it seems like a lot of code. Am I missing some obvious way of filtering/sorting on the "events" relationship of the Customer object or is creating the NSFetchRequest the best solution?


This is actually pretty simple because of the KVO and KVC accessors that are available on NSSet and NSArray.

NSSet *eventsWithAddress = [[customer valueForKey:@"events"] filteredSetWithPredicate:[NSPredicate predicateWithFormat:@"address != nil"]];
id mostRecentEvent = [eventsWithAddress valueForKeyPath:@"@max.lastDate"];

Of course the property name is up to you since I cannot see your data model but that gives you a general idea of where the code needs to go. You can see what operators are available in Apple's documentation.

http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/KeyValueCoding/Concepts/ArrayOperators.html

WARNING: Code written in StackOverflow comment window so you will most likely need to tweak it a bit.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜