Reputation: 452
I have a UITableView with 3 custom UITableViewCells that I'm currently dequeuing like so:
if (indexPath.row == 0) {
static NSString *CellIdentifier = @"MyCell1";
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
return cell;
}
if (indexPath.row == 1) {
static NSString *CellIdentifier = @"MyCell2";
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
return cell;
}
if (indexPath.row == 2) {
static NSString *CellIdentifier = @"MyCell3";
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
return cell;
}
I've tried to do this multiple ways, but the problem is even though I'm still dequeueing them all with different identifiers, when I scroll the tableView around, sometimes my first cell appears in the location of my third cell and viceversa. There seems to be some weird caching going on.
Does anyone know why? Thanks.
Upvotes: 0
Views: 1107
Reputation: 9768
Since you are always allocating the same cell classes, there is no point to the code you posted. The cell identifiers are not used to identify the specific cell, but the subclass you are using.
So change the code to:
static NSString *CellIdentifier = @"MyCell";
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
return cell;
and set up the cell contents properly in willDisplayCell based on indexPath.section and indexPath.row:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
Upvotes: 1