iOS UITableView numberOfRowsInSection BAD ACCESS



我在heightForRowAtIndexPath内调用UITableView委托的numberOfRowsInSection方法,但它给了我一个错误的访问错误

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ...
    NSLog(@"number of rows in section: %i", [tableView numberOfRowsInSection:[indexPath section]]);
    ...
}

谁能告诉我这里出了什么问题?

您正在调用委托方法。

调用此方法时,它将调用相关的委托方法,如cellForRowAtIndexPathheightForRowAtIndexPath等。

会导致无限循环,这就是它崩溃的原因。

您需要

在此处返回一个实际值。因此,与其打电话给[tableView numberOfRowsInSection:[indexPath section]]不如再次做同样的事情。

为了不重复你的代码,你可以创建一个可以在两个地方调用的帮助程序方法,即你的heightForRowAtIndexPath方法和numberOfRowsInSection方法:

- (int) myNumberOfRowsMethod{
    // Here you would usually have some underlying model 
    return [self.myContactsOrWhateverArray count];
}

很正常。在那一刻,你的UITableView正在被创造。在构建之前,您不应该调用与UITableView相关的方法。您应该依靠其他机制来获得单元格的高度。

你正在打电话

[tableView numberOfRowsInSection:section];

你应该打电话

[self numberOfRowsInSection:section];

最新更新