Iphone 为UITableViewCell-array或switch语句选择字符串?
在设置UITableView的数据源时,我很想查看哪个更好,解决方案a:Iphone 为UITableViewCell-array或switch语句选择字符串?,iphone,cocoa-touch,uitableview,Iphone,Cocoa Touch,Uitableview,在设置UITableView的数据源时,我很想查看哪个更好,解决方案a: NSString *labelText; switch (indexPath.row) { case 0: labelText = @"Setup New Match"; break; case 1: labelText = @"Teams"; break; case 2: labelText = @"Players"
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];
我的干扇倾向于解决方案B,但我在每个循环上创建一个数组,只是为了提取一个对象。使用这两种解决方案中的任何一种都有什么特别的原因,还是仅仅是个人偏好?如果您喜欢使用解决方案B,您可以将标签数组设置为静态,这样可以消除每次创建数组的开销
就哪一个更好而言,虽然B在这个简单的例子中无疑是最优雅的,但它也是最不灵活的。图像在一种情况下,您可以对每个单元格进行更改以放置不同的图像,选项a使此更改更干净、更易于维护。如果您喜欢使用解决方案B,可以将标签数组设置为静态,这样可以消除每次创建数组的开销 就哪一个更好而言,虽然B在这个简单的例子中无疑是最优雅的,但它也是最不灵活的。图像在一种情况下,您可以对每个单元格进行更改以放置不同的图像,选项a使此更改更干净、更易于维护。我更喜欢解决方案a 除非你的数组是预先退出的,否则我不会使用B。也就是说,我正在开发一个带有分区的应用程序,并使用switch语句确定哪个分区,然后用预先存在的数组中的数据填充它。我更喜欢解决方案a
除非你的数组是预先退出的,否则我不会使用B。也就是说,我正在开发一个带有分区的应用程序,并使用switch语句确定哪个分区,然后用来自预先存在的数组的数据填充它。当我这样做时,我使用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];
}
执行此操作时,我使用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];
}
很好的妥协。当我不使用UITableViewGrouped时,我会这样做。很好的折衷。当我不使用UITableViewGroup时,我会这样做。