使用Core Data计算一个简单的和 [英] Calculating a simple sum with Core Data

查看:72
本文介绍了使用Core Data计算一个简单的和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Core Data存储,其实体Cost具有整数属性value。我想汇总我的商店中的所有成本,这相当于下面的sql语句:

I have a simple Core Data store with an entity Cost with an integer property "value". I want to sum up all amounts of the costs in my store, which is equivalent to the following sql statement:

SELECT sum(value) FROM costs

如何在Cocoa Touch中以最有效的方式使用Core Data?

How do I do it the most efficient way in Cocoa Touch? By using Core Data? Or just get all cost entities and do the summation manually?

推荐答案

最好的方法是使用获取特定值和供应a 具有 sum:函数的NSExpressionDescription。

The best way is to use a fetch for specific values and supply a NSExpressionDescription with a sum: function.

执行提取时,您将获得一个包含字典的一个元素数组,其字符串与表达式描述匹配,其值是表达式的结果。在这种情况下,您会得到一个 sum 键,其值将是给定表达式的属性的总和。

When you execute the fetch you get a one element array containing a dictionary whose keys match the expression descriptions and whose values are the results of the expressions. In this case, you would get a sum key whose value would be the sum of the attributes given the expression.

这篇关于使用Core Data计算一个简单的和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆