在indexPath的行高设置中,出现EXC Bad Access错误。

3

当我进入下面的 if 语句时,我收到了一个 EXC Bad Access 错误。令人沮丧的是,我已经确认 indexPath 和 tableView 指向了正确的位置。而且,在我的代码中的同一实现文件中,完全相同的 if 语句在其他地方使用时没有出现错误。

希望能得到帮助。

-(CGFloat)tableView:(UITableView *)tableView 
heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row] == ([tableView numberOfRowsInSection:[indexPath section]]-1))
    {
        return 44.0;
    } else {
        return 60.0;
    }                       
}

你在尝试什么?44.0和60.0行高的条件是什么? - TheTiger
我正在尝试使一个部分中的最后一项的行高为44个点,但我想保持所有其他行的高度为60个点。因此,如果[indexPath row]与该部分中的行数相同,则它是最后一个,我应该返回唯一的行高。这可能不是解决这个问题的最佳方法。但在这一点上,我已经花了很多时间来确定这个错误的根本原因,所以我仍然想把它解决掉。 - spikeymango
请展示异常堆栈跟踪。 - Hot Licks
@HotLicks 这个问题是来自2012年的... - erdekhayser
@erdekhayser - #*&% 僵尸!! - Hot Licks
你正在通过添加以下代码行无限地调用numberOfRowsInSection方法 -> [tableView numberOfRowsInSection:[indexPath section]]。 - Maverick
6个回答

0
根据您的逻辑,第一个部分(第0部分)中的行数应该为-1,即[indexPath section]-1

"-1" 的意图是匹配基数和名词性数字。 - spikeymango
所以,我的意思是将出现为0或1的行与包含1或2的部分的行数匹配。这个逻辑正确吗? - spikeymango
这里的部分可能有任意数量的行,取决于您定义了多少...这不是一般逻辑,因为它涉及到您在TableView中定义的部分和行数。 - Abhishek Singh

0
[indexPath section]-1 for section with index "0" is giving you bad access. Remove -1 from this statement. [indexPath section]-1对于索引为“0”的部分导致您访问错误。 从此语句中删除-1。

这是错误的。操作是从一个部分的行数中减去1,而不是从部分索引中减去1。请注意标点符号。 - rdelmar
在你的语句中,你首先从indexPath中获取部分编号,然后从该值中减去1。在所有这些操作之后,你试图获取索引为[indexPath section]-1的行,对于section = 0的情况,它将是-1 - Maksim
不是的,我已经测试过了,将日志语句放置在didSelectRowAtIndexPath方法中:NSLog(@"numRowsInSction = %d",([tableView numberOfRowsInSection:[indexPath section]]-1)); ,它可以正确地记录我所点击的部分的行数减1。如果你说得对,那么当我点击第0段时应该会出现错误。无论如何,去掉-1也不能解决问题。 - rdelmar

0
一个更好的解决方案是不要询问 TableView 某个 section 中有多少行,而是询问你的数据源中有多少行。

例如,如果你的数据源是一个数组,那么就检查 array.count(当然,你肯定有其他数据源,因为你有分区,不过你明白我的意思)。

好的观点!所以我正在向视图请求数据,然后视图转过身去问控制器,控制器又转身问数据源,但我本可以直接去找数据源。我想知道这是否是我得到如此奇怪错误的原因。 - spikeymango
希望这能解决你的问题。个人认为自己调用 UITableViewDelegate 方法是一种不好的做法,可能会给你带来严重的麻烦 ;) - iTukker

0
if([indexPath row] == ([tableView numberOfRowsInSection:[indexPath section]-1]))
    {
        return 44.0;
    } else {
        return 60.0;
    }            

0

我知道这是一个老问题,但对未来的其他人可能有所帮助。

解决方案:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger numOfRowsInSection = [tableView.dataSource tableView:tableView numberOfRowsInSection:indexPath.section];
    if (indexPath.row == (numOfRowsInSection - 1))
        return 44.0;
    else
        return 60.0;
}

解释:

发生的情况是每次调用[tableView numberOfRowsInSection:[indexPath section]]时,系统都会再次调用[tableView heightForRowAtIndexPath:indexPath],从而创建一个无限循环,最终导致应用程序崩溃。

使用tableViewdataSource属性来防止循环,像这样:

[tableView.dataSource tableView:tableView numberOfRowsInSection:[indexPath section]]

-1
你正在使用一个tableView代理方法。试试这个方法代替:
 if([indexPath row] == ([self tableView:tableView numberOfRowsInSection:indexPath.section]-1))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接