【问题标题】:substitute to switch statement in objective c替代目标 c 中的 switch 语句
【发布时间】:2011-11-11 06:00:48
【问题描述】:

我正在使用异步连接中的 json 框架从 web 服务中加载内容的 tableview。数据为json对象形式

 {"id":1,"firstName":"A","lastName":"B","email":"abc@yahoo.com","salary":    {"monthly":$5000,"annual":$60000}}

我正在使用 cellForRowAtIndexPath 中的 switch 语句加载 tableview:

 dictionaryData = [responseString JSONValue];
switch (indexPath.row)
{


case 0:
    cell.textLabel.text = [NSString stringWithFormat:@"%@ : %@ %@",@"Name",[dictionaryData valueForKey:@"firstName"],[dictionaryData valueForKey:@"lastName"]];
    break;

    case 1:
        cell.textLabel.text = [NSString stringWithFormat:@"%@ : %@",@"Email",[dictionaryData valueForKey:@"email"]];
        break;

    case 2:
        cell.textLabel.text = [NSString stringWithFormat:@"%@ : %@",@"Monthly Salary",[[dictionaryData valueForKey:@"salary"]valueForKey:@"monthly"]];;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        break;

    case 3:
        cell.textLabel.text = [NSString stringWithFormat:@"%@ : %@",@"Annual Salary",[[dictionaryData valueForKey:@"salary"]valueForKey:@"annual"]];
        break;

    default:
        break;
}

这是针对普通数据的,但是当我有更多的字段,如电话号码、地址、部门号码等时,写太多的案例会使方法变得非常大。有人可以帮我如何在不切换的情况下做到这一点。

【问题讨论】:

    标签: ios4 xcode4


    【解决方案1】:

    你这样做是错误的。您想创建数组并使用 indexpath.row 对它们进行索引。因此,您将只有一行分配 cell.textLabel.text。一种解决方案是: 事先创建一个 NSArray 对象,其中包含您的 @"Name"、@"E-Mail" 等,例如:

    NSArray *arr1=[NSArray arrayWithObjects:@"Name",@"Email",....,nil];
    

    然后当你得到 NSDictionary 时,将它存储在一个数组中并像这样枚举它

    NSMutableArray *arr2=[dictionaryData allValues];
    for(id obj in arr2)
    {
        if([obj isKindOfClass:[NSString class]])
            [arr2 addObject:obj];
        else if([obj isKindOfClass:[NSDictionary class]])
        {
            [arr2 addObject:[obj valueForKey:@"Monthly"]];
            [arr2 addObject:[obj valueForKey:@"Annual"]];
        }
    }
    

    然后在 cell.textLabel.text 中使用 indexpath.row

    cell.textLabel.text=[NSString stringWithFormat:@"%@ : %@",[arr1 objectAtIndex:indexPath.row],[arr2 objectAtIndex:indexPath.row]];
    

    当然,针对您的情况可能会有更好的方法,但这应该可以帮助您构建它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-18
      • 2011-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多