Nyxynyx
Nyxynyx

Reputation: 63619

Unused variable when if() is introduced

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

Upvotes: 0

Views: 518

Answers (1)

zoul
zoul

Reputation: 104065

I think you have to drop the UITableViewCell * inside the conditional block. Otherwise you are declaring a new cell variable 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:

UITableViewCell *cell = /* try to get a cached one */
if (cell == nil) {
    cell = /* there was no cached cell available, create a fresh one */
}
/* …more code… */
/* and finally return the created cell */
return cell;

Upvotes: 6

Related Questions