iOS UITableView numberOfRowsInSection BAD ACCESS

2019-08-29 07:52发布

I'm calling the numberOfRowsInSection method of the UITableView delegate inside of the heightForRowAtIndexPath but it gives me a Bad Access Error:

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

Can anybody tell me whats wrong here?

4条回答
叼着烟拽天下
2楼-- · 2019-08-29 08:15

You need to return an actual value here. So instead of calling [tableView numberOfRowsInSection:[indexPath section]] simply do the same thing again.

In order not to duplicate your code you could create a helper method which you can call in both places, namely, your heightForRowAtIndexPath method and the numberOfRowsInSection method:

- (int) myNumberOfRowsMethod{
    // Here you would usually have some underlying model 
    return [self.myContactsOrWhateverArray count];
}
查看更多
The star\"
3楼-- · 2019-08-29 08:18

You are calling

[tableView numberOfRowsInSection:section];

You should be calling

[self numberOfRowsInSection:section];
查看更多
SAY GOODBYE
4楼-- · 2019-08-29 08:20

That's normal.. In that moment your UITableView is being created. You shouldn't call methods related to your UITableView, before it has been build. You should rely in other mechanism to get the height of your Cells.

查看更多
成全新的幸福
5楼-- · 2019-08-29 08:35

You are calling an delegate method.

When you call this method, it'll invoke the related delegates method like cellForRowAtIndexPath, heightForRowAtIndexPath etc.

It'll cause an infinite loop that's why it's crashing.

查看更多
登录 后发表回答