开发者

Simplifying switch statement (Objective-C)

开发者 https://www.devze.com 2022-12-19 12:32 出处:网络
I am trying to simplify a switch-statement that takes a lot of space and time to write. Se the code, you\'ll understand. If not, I\'ll explain later.

I am trying to simplify a switch-statement that takes a lot of space and time to write. Se the code, you'll understand. If not, I'll explain later.

// 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;
    }
}

Is there any way of simplifying th开发者_C百科is? Just do like,

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

For the record, I tried that, and it did not work.


The format specifier for an integer is %d%@ specifies an object. To be safe, you should also cast the NSInteger to an int when you pass it to printf() (so you would write @"%d", (int)row), because the size of NSInteger is not guaranteed to be the size the %d specifier tells printf() to expect.

Incidentally, you don't need to repeat it for each case statement. Without a break, control will fall through to the next case.


Like Chuck said you can do...

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

...or you can get fancy and turn it into an object...

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

精彩评论

暂无评论...
验证码 换一张
取 消