2

我正在尝试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,不是吗?

我很困惑,真的。

4

1 回答 1

2

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

于 2012-01-19T07:56:58.677 回答