Core Data get sum of values. Fetched properties vs. propagation

时间秒杀一切 提交于 2019-11-30 10:20:25

If you use a fetched property you cannot then query on that property easily without loading the data into memory first. Therefore I recommend you keep the actual de-normalized data in the entity instead.

There are actually a few ways to easily keep this up to date.

  1. In your -awakeFromFetch/-awakeFromInsert set up an observer of the relationship that will impact the value. Then when the KVO (Key Value Observer) fires you can do the calculation and update the field. Learning KVC and KVO is a valuable skill.

  2. You can override -willSave in the NSManagedObject subclass and do the calculation on the save. While this is easier, I do not recommend it since it only fires on a save and there is no guarantee that your account object will be saved.

In either case you can do the calculation very quickly using the KVC Collection Operators. With the collection operators you can do the sum via a call to:

NSNumber *sum = [self valueForKeyPath:@"transactions.@sum.startingBalance"];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!