Friday, June 7, 2013

UITableView registerClass forCellReuseIdentifier example in Objective C (iOS).


UITableView registerClass forCellReuseIdentifier

Registers a class for use in creating new table cells.

- (void)registerClass:(Class)cellClass forCellReuseIdentifier:(NSString *)identifier

Parameters of [UITableView registerClass forCellReuseIdentifier]
cellClass
The class of a cell that you want to use in the table.
identifier
The reuse identifier for the cell. This parameter must not be nil and must not be an empty string.

Discussion of [UITableView registerClass forCellReuseIdentifier]
Prior to dequeueing any cells, call this method or the registerNib:forCellReuseIdentifier: method to tell the table view how to create new cells. If a cell of the specified type is not currently in a reuse queue, the table view uses the provided information to create a new cell object automatically.

If you previously registered a class or nib file with the same reuse identifier, the class you specify in the cellClass parameter replaces the old entry. You may specify nil for cellClass if you want to unregister the class from the specified reuse identifier.

UITableView registerClass forCellReuseIdentifier example.
Also, it might be better to send registerClass:forCellReuseIdentifier: in viewDidLoad, instead of doing it every time a cell is requested:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.tableView registerClass:<RegisteredClass> forCellReuseIdentifier:<ReuseIdentifier>];
}

Example of [UITableView registerClass forCellReuseIdentifier].
Here is an example for a plain UITableViewCell:

- (void) viewDidLoad {
   [super viewDidLoad];

   [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
}

UITableView registerClass forCellReuseIdentifier example.
In viewDidLoad, register the class, in your case, that's just the UITableViewCell class:

[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
Then, you can just do it like this in cellForRowAtIndexPath:

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    cell.textLabel.text = self.myArray[indexPath.row];
    return result;
}

End of UITableView registerClass forCellReuseIdentifier example article.