Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:]

来源:互联网 发布:中京现货交易软件 编辑:程序博客网 时间:2024/06/01 09:54

这几天一直在调试一个UITableView崩溃的bug,一直没什么头绪,后来找到一个断言报错信息:Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:]。


网上搜了一下,找到下面一篇文章,刚好解决了我的问题。

文章地址:http://blog.csdn.net/hamasn/article/details/8613593


Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:]

今天做一个tableView遇到一个这么个问题。

经过baidu google,终于找到正解。

因为

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath     *)indexPath
这个函数的返回值是个null!!
查stackoverflow 找到下面的解。

CellIdentifier I bet your cellForRowAtIndexPath is returning null.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath     *)indexPath{    static NSString *CellIdentifier = @"Photos";    /** NOTE: This method can return nil so you need to account for that in code */    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];    // NOTE: Add some code like this to create a new cell if there are none to reuse    if(cell == nil)    {        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];    }    NSString *string = [[self.photosInPlace objectAtIndex:indexPath.row]     valueForKeyPath:@"description._content"];    cell.textLabel.text = string;    return cell;}

That's probably why [UITableView _configureCellForDisplay:forIndexPath:] is failing... becausecellForRowAtIndexPath is returning a null value and then configureCellForDisplay is expecting aUITableViewCell.


通过解决这个错误,认识到一点:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法中一定要注意避免所返回的cell为nil的情况出现。实际上,从iOS5开始,一个表视图可以跟踪与特定的可重用标识符相关联的nib文件。UITableView的

dequeueReusableCellWithIdentifier:方法现在很智能,就算没有可用的单元,它也可以使用这个注册了的nib文件来加载一个新单元。这就意味着,只要我们为表视图注册了所有将要使用到的可重用标识符,dequeueReusableCellWithIdentifier:方法就会始终返回一个单元,它决不会返回nil。因此,我们可以删除那些用于检查cell为nil的代码行,因为这种情况永远不会发生。

所以,这里更好的做法是用如下方法来实现-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    static NSString *CellTableIdentifer = @"CellTableIdentifer";    //tableView注册nib文件    static BOOL nibsRegistered = NO;    if(!nibsRegistered)    {        UINib *nib = [UINib nibWithNibName:@"TableViewItemCell" bundle:nil];        [tableView registerNib:nib forCellReuseIdentifier:CellTableIdentifer];        nibsRegistered = YES;    }        TableViewItemCell * cell = [tabView dequeueReusableCellWithIdentifier:CellTableIdentifer];    cell.textLabel.text = @"xxxxx";    return cell;}