NSDateComponents周崩溃

时间:2012-01-19 07:52:11

标签: ios nsdate nscalendar nsdatecomponents week-number

我正在尝试使用以下代码获取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

当我取消注释周数部分时,其他组件工作正常:

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的属性,不应该吗?

我很困惑,真的。

1 个答案:

答案 0 :(得分:2)

-weekOfYear方法可以在NSDateComponents启动iOS 5.0,因此如果您尝试在早期操作系统版本上使用该方法,则会导致崩溃。