iOS engineer who likes clean, simple designs and sans-serif.

Loading

UITableView dequeueReusableCellWithIndentifier

Someone asked me about this the other day, so I thought I’d write a quick blog post about how to use dequeueReusableCellWithIndentifier vs. dequeueReusableCellWithIndentifier:withReuseIdentifier.

dequeueReusableCellWithIndentifier
In the past, when using the old method, the pattern was to check if the cell was nil and if so — to then instantiate it and customize it.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LLCellId forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:LLCellId];
        cell.separatorInset = UIEdgeInsetsMake(0.0, tableView.frame.size.width, 0.0, 0.0);
    }
    return cell;
}

 
dequeueReusableCellWithIndentifier:withReuseIdentifier
In iOS 6.0, Apple introduced the newer dequeueReusableCellWithIndentifier:withReuseIdentifier, which guarantees that a cell is returned if given a proper reuseIdentifier. With this newer method, you need to register the cell, probably in viewDidLoad, but it makes your cellForRowAtIndexPath a bit cleaner. This also mirrors what you would do in a UICollectionView.

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:LLCellId];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LLCellId forIndexPath:indexPath];
    return cell;
}

 
Personally, I like to start off with the old way since it’s easier to customize a cell without subclassing if I’m prototyping something. Then when I’m farther along, I may choose to subclass the cell and then I’d clean up and simplify the UITableView code.

Leave a Comment