I'm encountering a problem where tableView:numberOfRowsInSection:
is getting called, then a other methods are getting called that affect the underlying array, then tableView:cellForRowAtIndexPath:
gets called and crashes because the contents of the underlying array is different than when numberOfRowsInSection
was called. If the framework would call numberOfRowsInSection
right before calling cellForRowAtIndexPath
, there wouldn't be a problem.
Since I can't expect a fix in the framework in the short term, the easiest solution I'm looking at is returning a dummy cell if the underlying array doesn't contain the requested entry.
More details on how this problem occurs:
- App uses a tab bar controller.
- The root controller for each tab is a
UINavigationController
. - The view controller in question is invoked by pushing it开发者_Python百科 on the nav stack of the second tab bar item's nav controller.
- The viewWillAppear method of the view controller in question resets the underlying array and then calls
[_tableView reloadData]
. - The app delegate which implements UITabBarControllerDelegate implements the
tabBarController:didSelectViewController:
method and callspopToRootViewControllerAnimated:
on the view controller being selected. - The root view controller's viewWillAppear method calls a method on the view controller in question which affects the contents of the underlying array.
Steps to repro the problem:
- Start app.
- Tap second tab item.
- Tap to bring up view controller in question. Perform work on that view to fill the table.
- Tap first tab item.
- Tap second item.
At step five, here is the order of the calls:
- viewControllerInQuestion: viewWillAppear - reloads underlying array, calls [_tableView reloadData]
- viewControllerInQuestion: numberOfRowsInSection - returns 1
- App delegate: didSelectViewController - calls popToRootViewControllerAnimated
- secondTabBarRootViewController: viewWillAppear - calls method on viewControllerInQuestion that clears contents of underlying array
- viewControllerInQuestion: cellForRowAtIndexPath - crashes trying to access object at index 0 in underlying array.
Thanks for any help you can give me.
This turned out to be a problem with improper calls to reloadData on the table view. I inherited this code, but I'm new enough to iOS that I didn't understand the proper usage.
The code was calling [_tableView reloadData] in both loadView and in viewWillAppear. Removing both calls solved this particular problem.
I had a similar problem.
If you have an observer in your controller that calls reloadData
, use the viewWillAppear
method to add the observer and viewWillDisappear
to remove it.
精彩评论