问题描述
我有一个使用Core Data的程序。当在循环中添加每个实体的数值时,我有点作弊。我读了关于使用NSPredicate过滤数据,但我不知道如何操纵数据或如何结果甚至存储。谢谢。
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.
推荐答案
如果符合您的要求,您可以分两步完成。
You can do it in two steps, if that fits your requirements.
- 首先使用
NSPredicate
筛选您的数据,并将其全部保存在NSArray
。 - 然后使用带键值编码的复合运算符获取总和。
- First filter your data with your
NSPredicate
and keep it all in anNSArray
. - Then use a compound operator with Key-Value Coding to get the sum.
下面是一个如何做的例子。为了使其自包含,使用硬编码的数组而不是Core Data:
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"];
这里的诀窍是 @sum
运算符。您可以阅读(以及另外几个类似的运算符)。
The trick here is the @sum
compound operator. You can read about it (and another couple of similar operators) here.
这篇关于使用NSPredicate将所有值相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!