iOS UITableView numberOfRowsInSection BAD ACCESS

2019-08-29 08:00发布

问题:

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?

回答1:

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];
}


回答2:

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.



回答3:

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.



回答4:

You are calling

[tableView numberOfRowsInSection:section];

You should be calling

[self numberOfRowsInSection:section];