我想要做的是将UITableView
部分索引映射到相应的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)。我该如何正确地进行比较?
答案 0 :(得分:2)
而不是使用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];
答案 1 :(得分:0)
不要费心将index.section
转换为NSNumber
;直接使用它作为switch参数,如下所示:
switch (index.section) {
答案 2 :(得分:0)
哦,我一开始并没有看到你无法打开一个物体。它必须是整数类型,字符类型或枚举。
此外,您需要更改变量声明。裸露的初始化器不能在交换机中使用。用大括号{ }
包装案例以局部地定义变量声明。
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;
}
答案 3 :(得分:0)
在switch-case中:
index.section
[daySection integerValue]
在if-else中,NSNumber返回一个对象,因此将其与1(整数)进行比较会返回一个警告。
[daySection integerValue]
@1
或[daySection isEqualToNumber:@1]
[daySection isEqual:@1]
进行比较
醇>