Luca Luca - 1 month ago 5
iOS Question

Invalid nib registered for identifier ((null)) - nib must contain exactly one top level

I'm using a custom

UITableViewCell
. When I try to run my code, I got this exception stack and I can't understand the source of the problem:

terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'invalid nib registered for identifier ((null)) - nib must contain exactly one top level object which must be a UITableViewCell instance'


Please note I am not using Storyboard.

EDIT:

This is my relevant code which cause the problem according to the breakpoint:

[tableviewSupport registerNib:[UINib nibWithNibName:@"HotelCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:CustomCellCId];

Answer

I'm not quite sure what you are trying to do in your provided code. You will unload your nib in tableView:cellForRowAtIndexPath:. You can use the below code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // Assuming you set a reuse identifier "cellId" in the nib for your table view cell...
    HotelCell *cell = (HotelCell *)[tableView dequeueReusableCellWithIdentifier:@"cellId"];
    if (!cell) {
        // If you didn't get a valid cell reference back, unload a cell from the nib
        NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:@"HotelCell" owner:nil options:nil];
        for (id obj in nibArray) {
            if ([obj isMemberOfClass:[HotelCell class]]) {
                // Assign cell to obj
                cell = (HotelCell *)obj;
                break;
            }
        }
     }

     return cell;
}

Now, based on the error you posted, iOS is expecting a single object in the array, so the for loop may be unnecessary. I've done this by checking if [nibArray count] == 1 and then grabbing the objectAtIndex:0 and assigning it to cell instead of looping, and this works as well. But, if one day Apple decides to stick something else in that nibArray, a for loop protects you against that.