问题
I'm developing an app for iOS, and I can't find much documentation on the new NSFetchRequest setPropertiesToGroupBy: method.
I have a bunch of entity A objects that have relationships with multiple entity B objects.
I want to fetch all entity B objects that match a specific pattern and group them by entity A. This is so that I don't have a separate DB fetch for every entity A. The results would ideally be structured so that I could iterate over groups of equal entity As, and then would have all the entity Bs matching the pattern from one fetch request.
I can see that the setPropertiesToGroupBy: method should let me group by the inverse B->A relationship, and returns an array of NSDictionaries. But does that mean each item in the NSArray corresponds to one group by entity A? And that the corresponding NSManagedObject subclasses can be found somewhere in the NSDictionary?
回答1:
No it doesn't. There are two ways to do this:
- Use multiple requests
- Have one request to get all A entities where the inverse A->B relationship is in a group of Bs. Then include an
NSSortDescriptorto sort by B and separate the results in to groups.
The latter is probably quicker because an in-memory split avoids repeated DB accesses and fetch request parsing.
来源:https://stackoverflow.com/questions/8875868/does-nsfetchrequest-setpropertiestogroupby-return-all-entities-that-match