简化开关语句(Objective-C)

时间:2010-02-09 19:19:57

标签: iphone objective-c switch-statement uipickerview

我正在尝试简化一个需要大量空间和时间来编写的switch语句。查看代码,你会明白的。如果没有,我稍后会解释。

// When row is selected
- (void)pickerView:(UIPickerView *)pickerTimer didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

    switch (row) {
        case 0:
            NSLog(@"It obviously worked.0");
            break;
        case 1:
            NSLog(@"It obviously worked.1");
            break;
        case 2:
            NSLog(@"It obviously worked.2");
            break;
        case 3:
            NSLog(@"It obviously worked.3");
            break;
        case 4:
            NSLog(@"It obviously worked.4");
            break;
        case 5:
            NSLog(@"It obviously worked.5");
            break;
        case 6:
            NSLog(@"It obviously worked.6");
            break;
        default:
            NSLog(@"It did kindof work.NIL");
            break;
    }
}

有没有办法简化这个?只是喜欢,

NSLog(@"It did work! %@", row);

为了记录,我试过了,但它没有用。

2 个答案:

答案 0 :(得分:8)

整数的格式说明符是%d - %@指定一个对象。为了安全起见,当你将NSInteger传递给int时,你也应该将它转换为printf()(所以你会写@"%d", (int)row),因为NSInteger的大小不能保证是%d说明符的大小告诉printf()期望。

顺便说一下,您不需要为每个案例陈述重复它。如果没有休息,控制权将落到下一个案例中。

答案 1 :(得分:6)

像Chuck说你可以做......

NSLog(@"It did work! %d", row);

...或者你可以把它变成一个对象......

NSLog(@"It did work! %@", [NSNumber numberWithInt:row]);