UITableView中heightForRowAtIndexPath 产生 EXC_BAD_ACCESS 的原因

    有时, 在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;
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值