开发者

Does calling 'count' on a to-many CoreData relationship fault bring all objects in the collection into memory?

Say I have an Entity 'Employee' with a to-many relationship 'departments' to another entity 'Department'. If I have an instance of an Employee object and the departments collection is currently a fault, what is the most memory efficient way to get the count of departments?

Two obvious options are:

1) calling [myEmployee.departments count];

2) Constructing a fetchRequest to return only the Department objects whose matching 'employee' relationship points to my employee object and then calling countForFetchRequest:

Apart from the memory usage would either one of 开发者_运维技巧these methods be non-negligibly faster then the other?


Relationships are not fetched unless you have relationshipKeyPathsForPrefetching.

However, my best advice for you is to always implement your solution in the most straight-forward way, and THEN tackles performance issues later. Humans are notoriously bad at predicting performance problems.

One tool, that is very easy to use, is Instruments, which is included in Xcode.

You can easily run a test using both approaches, and actually compare numbers, rather than just take the opinion of some stranger on SO.


First: When the relationship is called the object are loaded as "fault" so the performance is so good.

Second: If you use countForFetchRequest method, the request would be:

NSFetchRequest *f = Departament.fetchRequest;

f.predicate = [NSPredicate predicateWithFormat:@"ANY employees = %@", employe.objectID];

so CoreData must check each department to look the employees. In the practise is more slower.

  • In your case I would use the first option.
  • The situation would be different if the predicate needs properties of the objects, so the first option needs the whole objects without fault. In this case I recommend to use countForFetchRequest, but the best option is compare in the particular case.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜