Buron
Buron

Reputation: 1233

Right CellIdentifier for the cell in UITableView

Can someone explain the difference between

static NSString* CellIdentifier = @"Cell";

and

NSString *CellIdentifier = [NSString stringWithFormat: @"Cell%i", indexPath.row];

When should I use the first one and where the second?

Upvotes: 2

Views: 2608

Answers (1)

N_A
N_A

Reputation: 19897

static NSString* CellIdentifier = @"Cell";

This identifier (assuming there are no others) will identify a pool of cells from which all rows will pull when they need a new cell.

NSString *CellIdentifier = [NSString stringWithFormat: @"Cell%i", indexPath.row];

This identifier will create a pool of cells for each row, i.e. it will create a pool of size 1 for each row, and that one cell will always be used for only that row.

Typically you will want to always use the first example. Variations on the second example like:

NSString *CellIdentifier = [NSString stringWithFormat: @"Cell%i", indexPath.row % 2];

would be useful if you want every other row to have a certain background color or something of that sort.

An example of how to properly setup cell creation from here:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row];
    cell.textLabel.text = [item objectForKey:@"mainTitleKey"];
    cell.detailTextLabel.text = [item objectForKey:@"secondaryTitleKey"];
    NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"imageKey"] ofType:@"png"];
    UIImage *theImage = [UIImage imageWithContentsOfFile:path];
    cell.imageView.image = theImage;

    return cell;
}

Upvotes: 4

Related Questions