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

后端 未结 1 2047
無奈伤痛
無奈伤痛 2020-12-30 16:15

I\'m relatively new to Core Data (coming from an SQLite background). Just finished reading the \'Core Data for iOS\' book but I\'m left with a number of baffling questions w

相关标签:
1条回答
  • 2020-12-30 16:40

    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"];
    
    0 讨论(0)
提交回复
热议问题