Last Updated: December 26, 2018
·
9.621K
· michaelmorrison

Automatically generate UITableViewCell reuse identifiers

Reuse identifiers are required by UITableViewCell in order to support the dequeueing of reusable cells by uniquely identifying cell types. Normally you create a unique string reuse identifier for each kind of cell you have, which works fine but falls clearly within the realm of "busy work." Here's an example:

static NSString *CellIdentifier = @"MyCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
  cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

In the vast majority of situations, what you really need out of a reuse identifier is uniqueness based upon the class type of a table cell. Knowing this, surely it's possible to conjure up a reuse identifier automatically using the table cell class, as opposed to creating a new string every time you use a cell. Something along the lines of this:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class])];
if (!cell) {
  cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([UITableViewCell class])];
}

This code, NSStringFromClass([UITableViewCell class]), converts the class property of UITableViewCell into a string, which provides a handy string representation of the class that is perfectly suitable as a reuse identifier. While this works great, the idea can be taken a step further with a category on UITableViewCell that handles the string-from-class conversion behind the scenes. And since it's a category, it will work for all classes derived from UITableViewCell. Here's what the code looks like with the new category:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[UITableViewCell reuseIdentifier]];
if (!cell) {
  cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[UITableViewCell reuseIdentifier]];
}

And here are the .h and .m files for the UITableViewCell+ReuseIdentifier category:

UITableViewCell+ReuseIdentifier.h

#import <UIKit/UIKit.h>


@interface UITableViewCell (ReuseIdentifier)

+ (NSString *)reuseIdentifier;

@end

UITableViewCell+ReuseIdentifier.m

#import "UITableViewCell+ReuseIdentifier.h"


@implementation UITableViewCell (ReuseIdentifier)

+ (NSString *)reuseIdentifier {
  return NSStringFromClass([self class]);
}

@end

Add those two files to your project, import UITableViewCell+ReuseIdentifier.h into your code, and you're ready to use reuseIdentifier to eliminate one little piece of table view drudgery!