动态切换语句:Objective-C

Dynamic switch statement: Objective-C

我有一组类别:

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

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

- (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结尾)需要是数组中类别的名称。

有人可以帮我做这个吗?

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