如何在Objective C中替换大量的if语句

时间:2012-02-20 13:59:15

标签: objective-c if-statement

此刻我有大量的if语句,如

    if ([dicIdentifer isEqualToString:CONF_KEY_CALLMETHOD]) {
    switch ([[settingDictionary objectForKey:PLIST_VALUE] intValue]) {
        case CASE_1:
            cell.detailTextLabel.text = SOME_TEXT_1
            break;
        case CASE_2:
            cell.detailTextLabel.text = SOME_TEXT_2
            break;
        case CASE_3:
            cell.detailTextLabel.text = SOME_TEXT_3
            break;
        case CASE_4:
            cell.detailTextLabel.text = SOME_TEXT_4
            break;
        default:
            break;
    }
} else if ([dicIdentifer isEqualToString:CONF_KEY_HTTPMETHOD]) {
    switch ([[settingDictionary objectForKey:PLIST_VALUE] intValue]) {
        case CASE_1:
            cell.detailTextLabel.text = SOME_TEXT_1
            break;
        case CASE_2:
            cell.detailTextLabel.text = SOME_TEXT_2
            break;
        case CASE_3:
            cell.detailTextLabel.text = SOME_TEXT_3
            break;
        case CASE_4:
            cell.detailTextLabel.text = SOME_TEXT_4
            break;
        default:
            break;
    }
} .....

我现在还有十多种此类“if”声明,而且这个数字可能会增加。这很有效,但在维护和效率方面,我认为可以改进。我从Ways to replace massive if statement with alternative construct in Objective-C读了一下帖子。但它似乎不适合我的情况。如果有人会对我的案子提出建议。

谢谢

1 个答案:

答案 0 :(得分:1)

您链接的问题中的方法非常适合此处。你只需要两个级别的词典:

NSDictionary *dictionaryForCallMethod = [NSDictionary dictionaryWithObjectsAndKeys:SOME_TEXT_1, [NSNumber numberWithInt:CASE_1], SOME_TEXT_2, [NSNumber numberWithInt:CASE_2], SOME_TEXT_3, [NSNumber numberWithInt:CASE_3], SOME_TEXT_4, [NSNumber numberWithInt:CASE_4], nil];
NSDictionary *dictionaryForHTTPMethod = [NSDictionary dictionaryWithObjectsAndKeys:SOME_TEXT_1, [NSNumber numberWithInt:CASE_1], SOME_TEXT_2, [NSNumber numberWithInt:CASE_2], SOME_TEXT_3, [NSNumber numberWithInt:CASE_3], SOME_TEXT_4, [NSNumber numberWithInt:CASE_4], nil];
// create additional dictionaries for each branch of your if statement

NSDictionary *bigDictionary = [NSDictionary dictionaryWithObjectsAndKeys:dictionaryForCallMethod, CONF_KEY_CALLMETHOD, dictionaryForHTTPMethod, CONF_KEY_HTTPMETHOD, nil];
// put the other dictionaries in this dictionary as well

cell.detailTextLabel.text = [[bigDictionary objectForKey:dicIdentifier] objectForKey:PLIST_VALUE];