替代目标C中的switch语句

我正在做一个项目,我正在从一个asynchronous连接的JSON数据加载表视图。 我正在使用switch语句来加载每一行,如下所示:

 dictionaryData = [responseString JSONValue]; switch (indexPath.row) { case 0: { NSString *name = [NSString stringWithFormat:@"%@ : %@ %@",@"Name",[dictionaryData valueForKey:@"firstName"],[dictionaryData valueForKey:@"lastName"]]; cell.textLabel.text = name; break; } case 1: { NSString *email = [NSString stringWithFormat:@"%@ : %@",@"Email",[dictionaryData valueForKey:@"email"]]; cell.textLabel.text = email; } break; 

有8行,我必须写8个开关的情况下,我认为使我的方法太长。 任何人都可以告诉我,有没有其他select切换语句。

在某些情况下,一个对象将是一个更好的select。

更新

我详细介绍了如何在这里(以一种过度工程的方式)来处理这个问题: 我可以使用什么替代switch语句来更新我的UITableViewCells?

用数组replace你的交换机。 数组中的每个索引都将对应于前case 。 数组应该用你需要的键来设置

 keyArray = [NSArray arrayWithObjects:@"Name", @"Email", ..., nil]; dictionaryData = [responseString JSONValue]; NSString * rowKey = [keyArray objectAtIndex:[indexPath row]]; [[cell textLabel] setText:[dictionaryData objectForKey:rowKey]]; 

switch的替代方法是使用一系列的if / else语句,这不会使代码变短。 如果你的方法太长或太复杂,将每个案例的主体移到它自己的方法中,然后从相应的案例中调用该方法。