Question

When setting up a UITableView's data source, I'd be interested to get views on which is better, solution 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;

or solution B?

NSArray *labels = [NSArray arrayWithObjects:@"String 1", @"String 2", @"String 3", @"String 4", nil];

cell.textLabel.text = [labels objectAtIndex:indexPath.row];

The DRY fan in me tends towards solution B, but then I'm creating an array on every loop just for the purpose of extracting one object. Is there any particular reason for using either solution over the other or is it just a personal preference?

Was it helpful?

Solution

When I do this, I use a switch statement. However, if you want to go with the array method and not create an array every time, you could use a static C array or something:

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

OTHER TIPS

If you are a fan of sticking with solution B you can make your labels array static which should eliminate the overhead of creating an array every time.

In terms of which one is better, though B is certainly the most elegant in this simple case it is also the least flexible. Image a situation where you make a change to put different images for each cell as well, option A makes this change much more clean and maintainable.

I prefer solution A.

Unless your array is pre-exiting I wouldn't use B. That said, I'm working on an app with sections, and use a switch statement to determine which section, then I fill it with data from pre-existing arrays.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top