Pheepster
Pheepster

Reputation: 6347

Custom UITableViewCell issue in UITableView

I have an app with a UIViewController containing a UITableView using a custom table view cell. I have used the same custom table view cell with UITableViewControllers successfully but this time it's a UITableView in a UIViewController. My first thoughts were that it really should be no different. However, for some reason, in my cellForRowAtIndexPath, upon initial loading, 'cell' is not nil, as it should be, so the code to instantiate the custom cell is never called.

I've created the custom cell both by using interface builder and by hand coding it with identical results. The only noticible difference is that the code works correctly when using it with a UITableViewController but fails when using it with a UIView containing a UITableView.

I have verified that my cell identifier is properly configured and my datasource and delegates are properly set in my UIViewController. The custom cell has its subclass properly set.

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

FaveCell *cell = (FaveCell*)[tableView dequeueReusableCellWithIdentifier:cellID];
if(cell == nil){
    // this line of code is never reached
    cell = [[FaveCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}

/* code to load controls

...

*/

return cell;
}

So, when the code enters cellForRowAtIndexPath for the first time, 'cell' should be nil, but it's not. Again, the only noticable difference being UIView/UITableView vs UITableViewController. Does this make sense to anyone? Can anyone offer a solution? Thanks!

Upvotes: 1

Views: 94

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

However, for some reason, in my cellForRowAtIndexPath:, upon initial loading, cell is not nil, as it should be, so the code to instantiate the custom cell is never called.

This is because UITableView became smarter as of iOS 5.0: if you tell it what kind of cells you want by specifying the custom cell type, it creates them for you, so the if(cell == nil) code is indeed never entered. From the documentation:

If the dequeueReusableCellWithIdentifier: method asks for a cell that’s defined in a storyboard, the method always returns a valid cell. If there is not a recycled cell waiting to be reused, the method creates a new one using the information in the storyboard itself. This eliminates the need to check the return value for nil and create a cell manually.

Upvotes: 2

Related Questions