Use NSPredicate to add up all values

試著忘記壹切 提交于 2020-01-11 11:49:34

问题


I have a program which uses Core Data. I was kinda cheating when adding the numeric values from each entity in a loop. I read about using NSPredicate to filter the data, but I don't know how to manipulate the data or how the results are even stored. Thanks.


回答1:


You can do it in two steps, if that fits your requirements.

  1. First filter your data with your NSPredicate and keep it all in an NSArray.
  2. Then use a compound operator with Key-Value Coding to get the sum.

Below is an example of how it can be done. To make it self-contained, a hard-coded array is used instead of Core Data:

// In reality this array would be the result of a Core Data query:
NSArray *numbers = @[@{@"number":@3},
                     @{@"number":@2}];

NSNumber *sum = [numbers valueForKeyPath:@"@sum.number"];

The trick here is the @sum compound operator. You can read about it (and another couple of similar operators) here.




回答2:


You can use NSExpressionDescription to have Core Data do the summing. I used this article as a tutorial when I was doing something similar.



来源:https://stackoverflow.com/questions/11927151/use-nspredicate-to-add-up-all-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!