cell重用时,老是提示找不到标识的cell,让我们注册cell

筅森魡賤 提交于 2019-12-26 18:42:55

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>


报错提示:

[9098:232849] *** Assertion failure in -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3512.30.14/UITableView.m:6564

2016-01-05 00:00:37.574 UI进阶考试微信[9098:232849] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier mineCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 创建可重用的cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] init];
    }
    
    return cell;
}


注意:上面的代码出错原因:

             1.没有给storyboard中的cell添加标识。

             2.如果是纯代码创建的UIStoryboard,在重用cell的时候,应该使用方法

- (nullable __kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier;



解决方法一:

   在storyboard中给cell添加标识,如果使用这种方法的话,就可以不用判断cell是否能从缓存池中找到,因为当从缓存池中找不到的话,就会使用storyboard中的cell。


解决方法二:

   cell重用的时候,使用方法

- (nullable __kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier;

再加上if判断

  if (cell == nil) {
        cell = [[UITableViewCell alloc] init];
    }

当从缓存池中找不到cell的时候,就会if判断语句的代码中重新创建。


总结:

   1、如果我们是用纯代码创建的UITableViewController的话,这时要创建可重用的cell的时候,一定要判断是否能从缓存池中找到,否则就会报错的!

   2、如果是在stroryboard中直接以拖拽的方式,创建的UITableViewController的话,最好给storyboard中的cell添加一个标识,以防出错。标识后我们就没必要再去判断cell是否能从缓存池中找到,因为即使找不到,系统也会自动的加载storyboard中的cell的。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!