从numberForRowAtIndexPath调用numberOfRowsInSection: [英] Calling numberOfRowsInSection: from heightForRowAtIndexPath

查看:98
本文介绍了从numberForRowAtIndexPath调用numberOfRowsInSection:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚在UITableView类中发现了一个非常奇怪和意外的行为。我需要在我的部分中的最后一个表格单元格与其他单元格的高度不同,所以我基本上这样做:

Just found a very strange and unexpected behavior in the UITableView class. I need the last table cell in my section to be a different height from the other cells, so I'm doing basically this:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section] - 1)
        return 44;
    else
        return 88; //double size for all but the last row
}

看起来非常简单,但是当我运行它时,我得到一个无限循环而且它崩溃了。我确定当我调用 numberOfRowsInSection:时,它会调用我的数据源的 tableView:numberOfRowsInSection:方法。这是有意义的,因为tableView的方法返回数据源值的缓存版本,因此它需要第一次从数据源获取值。但是,它调用heightForRowAtIndexPath,再次传递indexPath [0,0]!并且它不间断地发挥作用。

Seems pretty straight-forward, but when I run it, I get an infinite loop and it crashes. I determined that when I call numberOfRowsInSection:, it calls my datasource's tableView: numberOfRowsInSection: method. This makes sense as the tableView's method returns a cached version of the datasource value, so it needs to get the value from the datasource the first time. But then, it calls heightForRowAtIndexPath, passing it indexPath [0, 0] again! And it does this non-stop.

我能够通过使用

[self tableView:tableView numberOfRowsInSection:indexPath.section]

相反(调用我的数据源方法而不是tableView的方法)。任何人都知道它为什么这样做?这是定义的行为吗?或Apple的TableView框架中的错误?

instead (calling my datasource method instead of the tableView's method). Anyone have any idea why it does this? Is this defined behavior? Or a bug in Apple's TableView framework?

推荐答案

问题是UITableView正在向您的数据源询问数据,而您正在告诉它的答案取决于它可能或可能没有缓存的数据。

The problem is that the UITableView is asking your datasource for data, and you are telling it the answer depends on data it may or may not have cached.

您误解了Apple基于其控制的M-V-C布局。行高的答案应该来自您的模型,而不是来自回调到视图类。这导致视图类要求提供更多信息(构建其内部缓存),这将启动一组递归调用。

You're misunderstanding the M-V-C layout that Apple bases its controls on. The answer to the height of a row should come from your model, NOT from a call back to the view class. This is causing the view class to ask for more information (to build its internal cache), which is starting a set of recursive calls.

确保所有数据源委托方法都返回来自模型的数据,不依赖于缓存任何内容的视图。如果你调试任何基于数据源的视图,你会惊讶于UITableView请求数据的次数。但这就是Apple编码的方式。

Make sure all datasource delegate methods return data from your model and don't rely on the view caching anything. If you debug any datasource based view, you'll be surprised how many times a UITableView asks for data. But that's the way Apple coded it.

这篇关于从numberForRowAtIndexPath调用numberOfRowsInSection:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆