substitute to switch statement in objective c

2019-03-06 01:18发布

问题:

I am loading a tableview with the contents from web service using json frameworks in asynchronous connection. The data is in the json object form

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

I am loading tableview using switch statement in cellForRowAtIndexPath:

 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;
}

This is for normal data, but when i have more fields like phone number, address, department number, etc , then writing too many cases will make the method very large.Can someone help me how i can do this without switch.

回答1:

You are going about this the wrong way. You want to create arrays and index them using indexpath.row. So you ll have only one line of assigning cell.textLabel.text. One solution is: Create an NSArray of objects beforehand containing your @"Name",@"E-Mail" etc. like:

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

Then when you get the NSDictionary,store it in an array and enumerate through it like

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"]];
    }
}

Then just use indexpath.row in cell.textLabel.text

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

Of course there might be a better way specific to your case, but this should help you build that.



标签: ios4 xcode4