Joh*_*ith 0 cocoa-touch if-statement objective-c nsdatecomponents ios
我有一个iOS简单而合乎逻辑的应用程序if-statements.然而,他们不会运行,我不能理解为什么.这是我的简单代码:
-(void)viewDidLoad {
[super viewDidLoad];
// Run setup code.
int day = [self currentDay];
if ((day == (1 || 3 || 7) && (day != (2 || 4 || 5 || 6))) {
// Run the calendar setup code for
// Sunday/Tuesday OR saturday.
[self runSetupVX_4];
}
else if ((day == (2 || 4 || 5 || 6)) && (day != (1 || 3 || 7))) {
// Run setup code for Monday
// wednesday, thursday and friday.
[self runSetupVX_2];
}
}
-(int)currentDay {
NSDateComponents *component = [[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:[NSDate date]];
return [component weekday];
}
Run Code Online (Sandbox Code Playgroud)
我在这做错了什么?
这会编译,但它会与您尝试实现的完全不同:
day == (1 || 3 || 7) && (day != (2 || 4 || 5 || 6)
Run Code Online (Sandbox Code Playgroud)
在执行比较之前,语句OR为1,3和7,然后是OR 2,4,5和6.
正确的方法是分别比较day1,3和7.如果任何比较成功,也保证当天不是2,4,5或6:
if (day == 1 || day == 3 || day == 7)
...
if (day == 2 || day == 4 || day == 5 || day == 6)
...
Run Code Online (Sandbox Code Playgroud)
你也可以用以下内容重写switch:
switch(day) {
case 1:
case 3:
case 7:
// Run the calendar setup code for
// Sunday/Tuesday OR saturday.
[self runSetupVX_4];
break;
case 2:
case 4:
case 5:
case 6:
// Run setup code for Monday
// wednesday, thursday and friday.
[self runSetupVX_2];
break;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
250 次 |
| 最近记录: |