How to dequeue UITableViewCells

- by

Sometimes Xcode does a bit of magic behind the scenes which I don’t really understand.

Consider this standard table view method to display cells:

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

    // populate your cell
    
    return cell;
}

Where do we actually ever create a UITableViewCell? All we’re asking here is “do we have reusable ones available” – but if the answer is “no”, then somehow these get created without an error message. Other times (such as when using an overlay table view courtesy of the search display controller) we get an error message.

This brings me to the point that perhaps Xcode and iOS create as well as dequeue cells automatically – but when they don’t, here’s how we can do this manually.

Let’s amend the above code snippet:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    }

    // populate your cell
    
    return cell;
}

Now we properly create a cell should a dequeueable one not be available.

I haven’t had to use this, and the if statement never seems to get called if inserted into the Master/Detail template, yet I find this may be something to keep in mind for future projects.



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.