比较工作日 NSDate

Comparing Weekdays NSDate

我的目标:

我研究了这个主题,发现下面的代码是第一个 objective 的一种比较流行的方法。我在
找到了下面的代码 iPhone - how may I check if a date is Monday?
但是,出于某种原因,它会在我的代码中造成断点。它告诉我用 NSCalendarUnitWeekday 替换 NSWeekdayCalendarUnit(我这样做)并让 dayInt 成为 long(我试过),但这些仍然不起作用。
它构建但随后导致断点。如果 dayInt 是一个 int,它表示值为 0,但如果它是 long,则结果为 256。不过我真的不认为它需要很长。有任何想法吗?

NSDate* curDate = [NSDate date];
int dayInt = [[[NSCalendar currentCalendar] components: NSWeekdayCalendarUnit fromDate: curDate] weekday];

一旦我应用了您描述的更改,您的代码对我来说工作得很好:

NSDate* curDate = [NSDate date];
NSInteger dayInt = [[[NSCalendar currentCalendar] components: NSCalendarUnitWeekday fromDate: curDate] weekday];
NSLog(@"Today's day of the week = %ld", dayInt);

以下是我将其分解为更小的调试步骤的意思:

NSDate* curDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components;
components = [calendar components: NSWeekdayCalendarUnit fromDate: curDate];
NSInteger dayInt = 0;
dayInt = [components weekday];
NSLog(@"Today's day of the week = %ld", dayInt);

如果您让代码的每一行最多包含一个方法调用,那么在调试器中单步执行它并查看发生了什么会容易得多。上面的例子有点极端,但总的来说我更喜欢使用临时变量和一系列更简单的语句而不是大而复杂的语句。它使阅读和调试更容易,并且编译器优化了临时变量,因此性能几乎没有任何差异。