I’m currently learning on UITableViewCell using a book. In order to reuse cells when scrolling, the author asks to modify the original code to include a if() statement to check if the cell of a particular reuse identifier exists. However, after adding the if() statement, Xcode throws a warning that says Unused variable 'cell' on the line inside of if(!cell). When running the code, I get the error Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:' Did something go wrong?
Original Code
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"UITableViewCell"] autorelease];
Possession *p = [[[PossessionStore defaultStore] allPossessions] objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[p description]];
return cell;
}
Modified Code
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Check for reusable cell first, use that if it exists
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
// If there is no reusable cell of this type, create a new one
if (!cell) {
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"UITableViewCell"] autorelease];
}
Possession *p = [[[PossessionStore defaultStore] allPossessions] objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[p description]];
return cell;
}
I think you have to drop the
UITableViewCell *inside the conditional block. Otherwise you are declaring a newcellvariable inside the block and throwing it away instead of assigning to the cell declared above. (Didn’t the compiler warn you about that?) The overall logic should be: