我正在尝试使用此代码从NSDate中获取一年中的星期几:

int which = NSYearCalendarUnit | NSMonthCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekOfYearCalendarUnit | NSQuarterCalendarUnit;
NSDate* date= [NSDate date];
NSDateComponents* comps= [[NSCalendar currentCalendar] components:which fromDate:date];

today.weekNumber= comps.weekOfYear;

但是,由于某种原因,它崩溃了并说明:
reason: -[NSDateComponents weekOfYear]: unrecognized selector sent to instance
当我取消注释weeknumber部分时,其他组件也可以正常工作:
int which = NSYearCalendarUnit | NSMonthCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekOfYearCalendarUnit | NSQuarterCalendarUnit;
NSDate* date= [NSDate date];
NSDateComponents* comps= [[NSCalendar currentCalendar] components:which fromDate:date];

//   today.weekNumber= comps.weekOfYear;
today.month= comps.month;
today.year= comps.year;
today.quarter= comps.quarter;
today.hour= comps.hour;
today.minute= comps.minute;
today.second= comps.second;

根据文档,NSDateComponents应该具有一个名为weekOfYear的属性,不是吗?

我真的很困惑。

最佳答案

从iOS 5.0开始,-weekOfYear中提供了NSDateComponents方法,因此,如果您尝试在较早的OS版本上使用该方法,将会导致崩溃。

关于ios - NSDateComponents weekOfYear中的崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8922659/

10-14 22:28