NSFetchRequest按月分组 [英] NSFetchRequest group by month
问题描述
在我的模型中,我有一个Sale实体,每个Sale实体都有一个date属性(NSDate)。
我想计算每个月的销售额。
In my model, I have a Sale entity, each Sale entity has a date property (NSDate). I want to compute the sum of sales for each month.
我知道如何创建用于计算总和的表达式,我想找出的是
I know how to create the expression for computing the sum, what I want to find out is how do I tell NSFetchRequest to group by month.
推荐答案
您可以使用 NSFetchedResultsController
为您进行分组。它在工厂方法中有一个名为 sectionNameKeyPath
的参数,可用于分隔数据。您将免费获得所有 NSIndexPath
算法,以及无数的优化。
You can use a NSFetchedResultsController
to do the grouping for you. It has a parameter in the factory method called sectionNameKeyPath
which you can use to separate your data. You will get all the NSIndexPath
arithmetic for free, and a myriad of optimizations as well.
由于日期实际上是连续的,因此您必须使用瞬时属性,甚至必须保留月份数据(这很便宜,所以没关系)。看看Apple的示例代码,其中的节标题中带有日期,然后类似地进行。
Because dates are practically continuous, you have to work with transient properties, or even persist the month data (which is cheap, so it does not matter). Take a look at Apple's sample code with dates in section headers and proceed analogously.
Apple示例代码: DateSectionTitles
特别注意 APLEvent的实现。
Apple Sample Code: DateSectionTitles
Pay particular attention to the implementation of APLEvent.
这篇关于NSFetchRequest按月分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!