Tag Archives: iOS5 CocoaTouch Obj-C

iOS 5 and UITableView prototype cells

I was reading the post here which talks about how to use prototype cells, one of the new features in iOS 5.

In the section “Creating the TableView Datasource” we see this snippet of code in

 

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

    // Do stuff

    return cell;
}

This code is absolutely correct. But you want to use and explore all the goodies that iOS 5 has to offer you right? So here’s another one. I’ve been targeting iOS 5 prior to its public debut back in October, and like all of Apple’s betas before it, answers were hard to come by due to the NDA. So I spent a bunch of time digging around in the headers. One of the the things I came across was this little gem in UITableView.h

// Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one.
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier; 

// when a nib is registered, calls to dequeueReusableCellWithIdentifier: with the 
// registered identifier will instantiate the cell from the nib if it is not already in the reuse queue
- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_5_0);

When you create a prototype cell in a xib or storyboard that cell is already registered with the table view. So all you need to do is dequeue the cell, if one does not exist the tableView will instantiate one for you. So the above snippet now becomes this.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Do stuff

    return cell;
}

If you are stuck targeting iOS versions < 5 then you still need to do the nil check of course. Alternatively you could check out Matt Drance’s book iOS Recipies which illustrates how to get similar behavior out of your tableviews.

Tagged