动态切换语句:Objective-C

时间:2016-01-31 18:16:01

标签: ios objective-c arrays switch-statement

我有一系列类别:

["main", "category1", "category2", "category3"]

我目前正在执行以下操作,以便在选中时为每个列表项设置网址。

- (void)selectionList:(HTHorizontalSelectionList *)selectionList didSelectButtonWithIndex:(NSInteger)index{

    NSString *subCategoryURL = @"";
    tapCellIndex = -1;

    switch (index) {
        case 1: {
            subCategoryURL = [NSString stringWithFormat:@"%@%@/",CATEGORYURL,@"category1"];
        }
            break;
        case 2: {
            subCategoryURL = [NSString stringWithFormat:@"%@%@/",CATEGORYURL,@"category2"];
        }
            break;
        case 3: {
            subCategoryURL = [NSString stringWithFormat:@"%@%@/",CATEGORYURL,@"category3"];
        }
            break;
        case 0: {
            isMenuChoosed = NO;
            [self getHomePageDetails];
            return;
        }
            break;
        default: {
            subCategoryURL = [NSString stringWithFormat:@"%@%@/",CATEGORYURL,@"category1"];
        }
            break;
    }
    CategoryURL = subCategoryURL;
    [self getCategoryDeatils:subCategoryURL];
}

这样可以正常工作。但是,我的类别可能会更改列表中的位置,并且可能会添加或删除新类别,因此我需要将switch语句设置为动态。

例如,案例数量必须是数组中的项目数量,categoryX(以url结尾)需要是数组中类别的名称。

有人可以帮我这么做吗?

1 个答案:

答案 0 :(得分:0)

allCategories = @["main", "category1", "category2", "category3"]

如果您根据此数组创建按钮,则可以执行

    - (void)selectionList:(HTHorizontalSelectionList *)selectionList didSelectButtonWithIndex:(NSInteger)index{

        NSString *subCategoryURL = @"";
        if(![allCategories[index] isEqualToString:@"main"])
        {
             subCategoryURL = [NSString stringWithFormat:@"%@%@/",CATEGORYURL,allCategories[index]];
        }
        else
        {
             //main here
             return;
        }

    CategoryURL = subCategoryURL;
    [self getCategoryDeatils:subCategoryURL];
}