如何使用 NSNumbers 在 switch 语句中设置 NSDate

How to use NSNumbers to set an NSDate in a switch statement

我想做的是将 UITableViews 部分索引映射到相应的 NSDate,我本来想这样做的:

-(BOOL)whatSectionsAreVisible {
    NSArray *visibleRowIndexes = [self.agendaTable indexPathsForVisibleRows];
    for (NSIndexPath *index in visibleRowIndexes) {
        NSNumber *daySection = @(index.section);

        // Here is where I will map every index.section to an NSDate
        static NSDateFormatter *dateFormatter = nil;
        if(!dateFormatter){
            dateFormatter = [NSDateFormatter new];
            dateFormatter.dateFormat = @"yyyy-MM-dd"; // Read the documentation for dateFormat
        }



        if (daySection == 0){
            NSDate *date = [dateFormatter dateFromString:@"2015-06-01"];
        }
        else if (daySection == 1){
            NSDate *date = [dateFormatter dateFromString:@"2015-06-02"];
        }

        //... and so on

}

然而,使用 if 语句执行此操作 30 天会变得非常冗长,我认为对于这种情况使用 switch 语句会更有意义。我无法弄清楚如何设置 switch 语句的语法,我试过这样做:

switch (daySection) {
            case 0:
                NSDate *date = [dateFormatter dateFromString:@"2015-06-01"];
                break;

            case 1:
                NSDate *date = [dateFormatter dateFromString:@"2015-06-02"];
                break;

            default:
                break;
        }

但是第一行给我错误 Statement requires expression of integer type ('NSNumber *__strong' invalid)。如何正确设置此语句?

旁注: else if (daySection == 1) 行警告我正在比较指针和整数(NSNumber 和 int)。我该如何正确地进行比较?

不要费心将 index.section 转换为 NSNumber;直接将其用作开关参数,如下所示:

switch (index.section) {

与其使用 dateFromString 初始化程序,不如直接从组件构建日期,并完全避免 switch

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:daySection.intValue]; // <<== Extract int from daySection
[comps setMonth:6];
[comps setYear:2015];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];

哦,我一开始没看到,你不能打开一个对象。必须是整型、字符型或枚举型

此外,您需要更改变量声明。不能在开关中使用裸初始化器。用花括号 { } 将 case 括起来以在局部范围内定义变量声明。

switch ([daySection integerValue]) {
    case 0: {
        NSDate *date = [dateFormatter dateFromString:@"2015-06-01"];
        break;
    }
    case 1: {
        NSDate *date = [dateFormatter dateFromString:@"2015-06-02"];
        break;
    }
    default:
        break;
}

在开关盒中:

  1. 直接使用index.section
  2. 使用[daySection integerValue]

在 if-else 中,NSNumber returns 一个对象,因此将其与 1(整数)returns 进行比较会发出警告。

  1. 使用[daySection integerValue]
  2. 将其转换为整数
  3. 使用 [daySection isEqualToNumber:@1][daySection isEqual:@1]
  4. 将 NSNumber 与对象 @1 进行比较