erica / iphone-3.0-cookbook-

Sample Code
912 stars 305 forks source link

Chapter 19 Queried Color List crashes on scroll after search is canceled (possible fix?) #1

Closed jluckyiv closed 14 years ago

jluckyiv commented 14 years ago

When you run the app, search works perfectly. However, if you scroll your results (or click Search to resignFirstResponder), then touch the Cancel button without clearing the searchBar text, the TableView doesn’t update correctly and the app crashes on scroll, e.g.,

'NSRangeException', reason: '*\ -[NSCFArray objectAtIndex:]: index (2) beyond bounds (2)'

This bug only occurs if you scroll (or otherwise resignFirstResponder) after the search without manually clearing the searchBar text before hitting Cancel. I couldn’t figure out what caused this, but I found a solution (I think).

Now the app seems to deal with the Cancel button correctly.

erica commented 14 years ago

Testing and fixing per suggestion. Credit being given as jluckyiv. Please let me know if you want your real name used. Thanks.

jluckyiv commented 14 years ago

I'm sorry if this is a dupe. I thought I commented yesterday, but I guess it didn't take.

Using my real name, Jack Lucky, is fine. But after some more research, I think my solution was really a workaround. After reading the documentation for UISearchDisplayController, I think the problem is that when tableView:numberOfRowsInSection: fires, there is a disconnect between it and [tableView reload].

The documentation suggests this pattern:

I took a slightly different approach:

-(void)refreshTableView { [self performFetch]; if (searchBar.text && searchBar.text.length) { [self.searchDC.searchResultsTableView reloadData]; } else { [self.tableView reloadData]; }
}

I hope this is helpful. I didn't commit it through github because I'm only familiar with Subversion and I don't have enough confidence in my coding to commit something without you vetting it.

Thanks again for your book/code. I'll be buying the second edition the day it comes out.