热门标签 | HotTags
当前位置:  开发笔记 > 前端 > 正文

UITableView中heightForRowAtIndexPath产生EXC_BAD_ACCESS的原因

有时,在UITableView中cell的内容是动态变化的,因此cell的高度要根据内容调整。这个调整通过heightForRowAtIndexPath这个委托方法来完成。于是,

    有时, 在UITableView中cell的内容是动态变化的,因此cell的高度要根据内容调整。这个调整通过 heightForRowAtIndexPath 这个委托方法来完成。


    于是,依照网上别人的方法在 heightForRowAtIndexPath 函数中调用 cellForRowAtIndexPath如下:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    static NSString *CellIdentifier = @"WBStatusesCell";   //  获得cell的identifify    WBStatusesCell *cell = [tableView cellForRowAtIndexPath:indexPath]; //  调用cellForRowAtIndexPath获得一个cell实例        WBStatuses *statuses = [self.statuses objectAtIndex:indexPath.row]; //  self.statuses是一个NSMutableArray,为UITableView提供数据    [cell contentWithWBStatuses:statuses];           //  向cell动态加入View    return cell.frame.size.height;                   //  返回cell的高度}


     程序一运行,崩溃。出现 EXC_BAD_ACCESS(code=2 address=0xb7ffffcc)的错误,调试发现,程序一直在执行heightForRowAtIndexPath和cellForRowAtIndexPath两个函数,最终以EXC_BAD_ACCESS的错误,程序崩溃。

    网查找,在 http://stackoverflow.com/questions/12652761/exc-bad-access-in-heightforrowatindexpath-ios  找到答案。

    在UITableView显示之前调用heightForRowAtIndexPath计算每个cell的高度,进而在heightForRowAtIndexPath中调用cellForRowAtIndexPath。cellForRowAtIndexPath执行中又调用dequeueReusableCellWithIdentifierforIndexPath重用cell,但是开始时,没有cell可重用,于是创建新的cell,调用heightForRowAtIndexPath计算高度,这就形成了heightForRowAtIndexPath  和cellForRowAtIndexPath 的递归调用,最终程序崩溃。

    解决方法:在heightForRowAtIndexPath中不要调用cellForRowAtIndexPath,而是调用initWithStylereuseIdentifier获得cell实例,进而返回高度。代码如下:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"WBStatusesCell";
WBStatusesCell *cell = (WBStatusesCell *)[[WBStatusesCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; // WBStatusesCell 为定制的cell

WBStatuses *statuses = [self.statuses objectAtIndex:indexPath.row];
[cell contentWithWBStatuses:statuses];
return cell.frame.size.height;
}







推荐阅读
author-avatar
教坏的黑天使_203
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有