【问题标题】:Dynamic switch statement: Objective-C动态切换语句:Objective-C
【发布时间】:2016-05-09 03:11:40
【问题描述】:

我有一个类别数组:

["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 语句是动态的。

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

有人可以帮我做吗?

【问题讨论】:

  • "例如,case 的数量需要是数组中的项的数量" 那么就不能使用switch 语句。 switch 语句需要在编译时完全写出,但直到运行时你才知道类别的数量。
  • @matt 那么还有其他解决方案吗?

标签: ios objective-c arrays switch-statement


【解决方案1】:
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];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多