Dvole
Dvole

Reputation: 5795

Why did Apple change UITableViewCell working order?

Nowadays we have to use this code somewhere in ViewDidLoad -

[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:CellIdentifier];

and I am not sure what was wrong with old way by checking if cell was actually returned by queue in old method

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

What confuses me, is why use some arbitary method calls in irrelevant places, and what does this "register" method does anyway?

Upvotes: 0

Views: 94

Answers (1)

Alphapico
Alphapico

Reputation: 3043

It's since in iOS 5 that Apple introduced a short-cut method of instantiating cells from NIB files that has three stages:

  1. Declaring a property for the cell identifier
  2. Registering the NIB object that contains the cell, and associating that with the cell identifier
  3. Creating the cell itself (and then customizing the controls as usual)

Registering the NIB object needs to happen only once during the lifetime of the controller, so an obvious place to put the code is in the viewDidLoad method of the tableView’s controller:

cellIdentifier = @"CustomCell";
[tableView registerNib:[UINib nibWithNibName:@"customCell" bundle:nil]

This takes two parameters:

  1. A reference to an instance of UINib, which you get by passing in UINib’s nibWithNibName method
  2. The NSString cell identifier that was previously created

After the NIB is registered for use as a cell, the dequeueReusableCellWithIdentifier method will do one of two things:

  1. If there’s a cached cell available for reuse, it will be dequeued and can be accessed through the cell variable.
  2. If there isn’t a cell available for reuse, dequeueReusableCellWithIdentifier will create one from the registered NIB.

Both of these things take place behind the scenes, so there’s now no longer any need to do the check for the cell’s existence manually. dequeueReusableCellWithIdentifier will handle all that for you.

Upvotes: 2

Related Questions