简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM