BadBoolean
BadBoolean

Reputation: 35

TableView Crashes on reloadData - 'unrecognized selector sent to instance'

In my tableView's cellForRowAtIndexPath method, I use a custom cell for the first row and a regular UITableViewCell for the other rows:

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

    static NSString *MyIdentifier = @"Cell";

    if (indexPath.section == 0){
        CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];

        if (cell == nil)
        {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomTableViewCell" owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }

        cell.titleLabel.text = @"Custom cell";

        if (isLightTheme){
           cell.titleLabel.textColor = [UIColor blackColor];
        }
        else{
           cell.titleLabel.textColor = [UIColor whiteColor];
        }

        return cell;
    }
    else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:MyIdentifier];
        }

        cell.textLabel.text = @"Other cells";

        if (isLightTheme){
            cell.textLabel.textColor = [UIColor blackColor];
        }
        else{
            cell.textLabel.textColor = [UIColor whiteColor];
        }

        return cell;

    }

}

I then call a method that changes isLightTheme and reloads data:

-(void)changeTheme{

   isLightTheme = false;
   [self.myTable reloadData];
}

... but my app crashes on this line:

    cell.titleLabel.text = @"Custom cell";

with the error:

'-[UITableViewCell titleLabel]: unrecognized selector sent to instance

I don't understand what's going on.. the table loads perfectly fine (isLightTheme is first set to true) when the ViewController first loads, but when I change isLightTheme and reloadData it crashes. Could anybody help me out? Thanks.

Upvotes: 1

Views: 1066

Answers (1)

Mark McCorkle
Mark McCorkle

Reputation: 9414

Your reuse identifier is the same for both of your cells. The custom and the default. Use unique values for each.

Upvotes: 3

Related Questions