核心数据组NSDate的月份/年份 [英] Core Data group NSDate into month/year
问题描述
假设我在表中有一些NSDates:
Suppose I have some NSDates in a table:
- 2012年1月11日
- 1/16/2012
- 2/14/2012
- 4/13/2012
- 4 / 14/2012
- 2012/4/18
- 1/11/2012
- 1/16/2012
- 2/14/2012
- 4/13/2012
- 4/14/2012
- 4/18/2012
我想将这些日期分组这样的月份和年份:
I would like to group these dates by month and year such that I get:
- 1/2012
- 2/2012
- 4/2012
我目前求助于获取表中的每个记录,并执行 valueForKeyPath
在日期列上,提取 NSDateComponents
并将结果存储在 NSSet
。这似乎效率很低。
I currently resort to fetching every record in the table, performing a valueForKeyPath
on the date column, extracting NSDateComponents
and storing the results in an NSSet
. This seems a bit inefficient.
我想知道是否有一种方法可以编写NSPredicate来将这些日期分组在数据库端。
I would like to know if there is a way to write an NSPredicate that will group these dates on the database side.
推荐答案
我做类似的事情,并且我在名为 sortDate
。
我从自定义日期设置器设置了sortDate。
I do something similar, and I use an extra attribute in the entity that is named sortDate
.
I set the sortDate from my custom date setter.
类似这样的东西:
- (NSDate *)monthDateFromDate:(NSDate *)date {
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit fromDate:date];
NSDate *monthDate = [calendar dateFromComponents:components];
return monthDate;
}
- (void)setDate:(NSDate *)date {
[self willChangeValueForKey:@"date"];
[self setPrimitiveStartDate:date];
[self didChangeValueForKey:@"date"];
NSDate *sortDate = [self monthDateFromDate:date];
[self willChangeValueForKey:@"sortDate"];
[self setPrimitiveSortDate:sortDate];
[self didChangeValueForKey:@"sortDate"];
}
这篇关于核心数据组NSDate的月份/年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!