问题
I have a core data with an Entity called "Expense", its like: Entity: "Expense" Attributes: "Date", "Category", "Amount"..........
My question is that is it possible to fetch how many expenses by year or year-month? I know if the fetch is based on time period or category, I can use NSPredicate to filter the fetched result. But the "Date" attribute in my mind should be seperated by year and month, so I can group them as in SQL query. Is it possible to do that directly in fetch? Otherwise the only way is to fetch the whole data to a NSArray and do some filters by NSPredicate.
I have searched this for days but find no direct answer. Now I actually kinda believe there is no direct solution. But I still think want to check out if anyone can provide me some better solution coz every developer must have solved this problem.
Any suggestion will be much appreciated, thank you guys :)
============================Added======================= Moreover, I would like to the feteched result based by "Year-Month" to be index-listed in UITableView, as far as I know about the technique about indexed list. I'm likely to provide every array with Expenses according to every indexed "Year-Month". Is there a better way to do that?
My thinking based on data structure is to build some to-many relationship, from Entity(year) to-many Entity(year,month,year-month) to-many Entity(year-month, Date, Amount....). Maybe this will bring me some convenience when I fetch every array for indexed UITableView.
回答1:
You can implement @readonly properties "year" and "month" in Expense class and then use them in predicate. You don't have to store these values separatel, just compute them in getters using NSDateComponents.
回答2:
Add three more attributes to store the date components in your entity (separate the date components as day,month and year then store these three entries) , and also have a date attribute to store complete date. when you want to fetch data by year or year-month just use predicate.
NSPredicate *filter = [NSPredicate predicateWithFormat:@"month=%d AND year=%d",month,year];
[request setPredicate:filter];
NSArray *results = [self.moContext executeFetchRequest:request error:nil];
if(results.count > 0) {
//do your manipulations.
}
来源:https://stackoverflow.com/questions/16475856/how-to-group-fetched-result-from-core-data-ios-dev