如何在核心数据中按星期几选择

时间:2012-06-21 01:55:08

标签: objective-c ios core-data

是否可以在Date属性上使用星期几来在Core Data中使用谓词?

例如在SQL中有DAYOFWEEK()函数。

我要做的是获得按星期几分组的平均分数,其中每个对象都有分数属性和日期属性。

我已经把注意力集中在分组部分,我只是找不到周日那天的任何信息。

1 个答案:

答案 0 :(得分:0)

您需要向核心数据实体添加瞬态属性。然后在实体的实现文件(NSManagedObject)中编写自定义代码。

在头文件中:

@property (readonly) NSString *weekDayText;
@property (readonly) NSInteger *weekDay; // use the number for sorting 

在实施文件中:

- (NSInteger)weekDay {
    // get the date from attribute
    // you declared in the header file also
    NSDate *event = self.scoreDate;

    // do some kind of test to make sure it's not null

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *weekdayComponents =[gregorian components:NSWeekdayCalendarUnit fromDate:event];

    NSInteger day = [weekdayComponents weekday];
    // weekday 1 = Sunday for Gregorian calendar

    [gregorian release];

    return day;
}

- (NSString *)weekDayText {
    NSInteger day = self.weekDay;
    // now you would use some kind of locale to return the proper string
    // for each language 
    NSString *text = .... // need to implement

    return text;
}