您的位置:首页 > 产品设计 > UI/UE

UITableView中heightForRowAtIndexPath 产生 EXC_BAD_ACCESS 的原因

2014-05-11 21:18 435 查看
有时, 在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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: