1

Say we have a entity Company that has a to-many relationship to the Employee entity via the employees.

If I want to find the last created Employee (assume Employee has a NSDate property created), which of these two approaches is better?

  • create a NSFetchRequest on Employee, restricted to "company == %@", someCompany, sort by created, and set the fetchLimit to 1
  • or use sortedArrayUsingDescriptors: on someCompany.employees with a NSSortDescriptor on created and take the first?

While the second approach seems more straight forwards, I'm concerned about the actual processing. The first approach would allow the system to tailor a custom query, while the second does some in-memory sorting? I guess it boils down to whether to-many relationships are lazy or not.

4

2 回答 2

2

In my personal experience I would take the first approach.

First of all you don't need to perform a two steps operation like the second. In addition, you can have full control of the element (you set the fetch limit to 1) you grab with the fetch request (e.g. you can specify the properties to retrieve using setPropertiesToFetch and delegate Core Data to fire faults for you).

Then, when you do someCompany.employees you retrieve few objects (say 20) that are faults (you grab first theirs skeleton) but they are in memory and they occupy it. When you apply a sort descriptor (maybe at that point some sort of fault will fired on them), you end up with 19 objects that are in memory but are not useful for the application lifecycle.

Personal Note

Even if I'm a good programmer, I would trust on Core Data framework optimizations and I would take the first way. :-)

Hope it helps.

于 2012-05-27T11:06:08.760 回答
0

Core Data uses lazy loading for this type of relationship. Thus, the first approach seems to be better. But I recommend filling your database with a lot of records and testing both of them. You may also want to read Core Data Performance section.

于 2012-05-27T09:14:29.767 回答