代码之家  ›  专栏  ›  技术社区  ›  Owain Hunt

选择uiTableViewCell-array或switch语句的字符串?

  •  0
  • Owain Hunt  · 技术社区  · 17 年前

    在设置UITableView的数据源时,我希望能够获得更好的视图,解决方案A:

    NSString *labelText;
    
    switch (indexPath.row) {
        case 0:
            labelText = @"Setup New Match";
            break;
        case 1:
            labelText = @"Teams";
            break;
        case 2:
            labelText = @"Players";
            break;
        case 3:
            labelText = @"Archive";
            break;
    }
    
    cell.textLabel.text = labelText;
    

    或解决方案B?

    NSArray *labels = [NSArray arrayWithObjects:@"String 1", @"String 2", @"String 3", @"String 4", nil];
    
    cell.textLabel.text = [labels objectAtIndex:indexPath.row];
    

    我中的dry fan倾向于解决方案B,但随后我在每个循环上创建一个数组,只是为了提取一个对象。有没有什么特别的理由比另一个使用解决方案,或者它只是一个个人偏好?

    3 回复  |  直到 17 年前
        1
  •  2
  •   Ed Marty    17 年前

    当我这样做时,我使用switch语句。但是,如果要使用array方法,而不是每次都创建数组,则可以使用静态C数组或其他方法:

    static NSString * const labels[] = {@"String 1", @"String 2", @"String 3", @"String 4"};
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        //Get the cell in the normal way.  No array stuff here
        //...
        cell.textLabel.text = labels[indexPath.row];
    }
    
        2
  •  1
  •   Greg Martin    17 年前

    如果你喜欢使用解决方案B,你可以使你的标签数组是静态的,这样可以消除每次创建数组的开销。

    就哪一个更好,虽然在这个简单的例子中,B当然是最优雅的,但它也是最不灵活的。想象一下这样一种情况,你也可以改变为每个单元格放置不同的图像,选项A使这种改变更加清晰和可维护。

        3
  •  1
  •   fearmint    17 年前

    我更喜欢解决方案A。

    除非你的数组是预先退出的,否则我不会使用b。也就是说,我正在开发一个带有节的应用程序,并使用switch语句来确定哪个节,然后我用预先存在的数组中的数据填充它。