Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

前端 未结 22 1300
长情又很酷
长情又很酷 2020-11-22 10:10

So I was making an rss reader for my school and finished the code. I ran the test and it gave me that error. Here is the code it\'s referring to:

- (UITableV         


        
22条回答
  •  攒了一身酷
    2020-11-22 10:46

    you have to be aware that when using interface builder and creating a Xib (nib) containing one cell that there is also a placeholder created that points to the class that will be used. Meaning, when you place two UITableViewCell in one Xib file you possibly run into the exact same trouble causing an *** Assertion failure .... The placeholder mechanism doesn't work adn will be confused then. Instead placing different placeholders in one Xib read on..

    The most easy solution (even if that seems a bit to simple) is to place one Cell at a time in one Xib. IB will create a placeholder for you and all works as expected then. But this then leads directly to one extra line of code, because then you need to load the correct nib/xib asking for the reuseIdentified Cell where it resides in. So the following example code focuses the use of multiple Cell Indentifiers in one tableview where an Assertion Failure is very common.

    // possibly above class implementation
    static NSString *firstCellIdentifier = @"firstCellIdentifier";
    static NSString *secondCellIdentifier = @"secondCellIdentifier";
    
    // possibly in -(instancetype)init 
    UINib *firstNib = [UINib nibWithNibName:@"FirstCell" bundle:nil];
    [self.tableView registerNib:firstNib forCellReuseIdentifier:firstCellIdentifier];
    UINib *secondNib = [UINib nibWithNibName:@"SecondCell" bundle:nil];
    [self.tableView registerNib:secondNib forCellReuseIdentifier:secondCellIdentifier];
    

    Another trouble with the use of two CellIdentifier's in one UITableView is that row height and/or section height have to be taken care of. Two cells can have different heights of course.

    When registering classes for reuse the code should look different.

    The "simple solution" looks also much different when your cells reside inside a Storyboard instead of Xib's. Watch out for the placeholders.

    Keep also in mind that interface builder files have version wise variations and need to be set to a version that your targeted OS version supports. Even if you may be lucky that the particular feature you placed in your Xib is not changed since the last IB version and does not throw errors yet. So a Xib made with IB set to be compatible to iOS 13+ but used in a target that is compiled on an earlier version iOS 12.4 will cause also trouble and can end up with Assertion failure.

提交回复
热议问题