Search code examples
iosasynchronousnsurlconnectionuisearchdisplaycontrollertype-ahead

Creating a type-ahead UISearchDisplay with asynchronous network calls in iOS


One view of my iOS application is a UISearchDisplay. I have designed it as a type-ahead search, so that whenever the user enters a new character the table is re-populated. I have done this by implementing the UISearchDisplayDelegate protocol method:

searchDisplayController:shouldReloadTableForSearchString:

In this method I take the string provided and append it to my query URL. I then create a new NSURLConnection and submit a new asynchronous request. I receive and append data via the delegate method:

connection:didReceiveData:

Once the connection has finished downloading the data, via the method:

connectionDidFinishLoading

I pass the data to an instance of NSXMLParser. The data that is receive is an XML file of all the contacts in my database which match the given string. Once the data has finished being parsed I reload the table.

My Problem: If the user types in text fast enough, there will be multiple connection and parsing tasks going on at the same time. This is an issue because I have one instance of NSMutableData which I append data to and parse. Hopefully you can see where I am going with this.

Does anyone have any suggestions for improving my implementation and/or solving this critical-section problem?


Solution

  • NSXMLParser is not asynchronous. This one trips a lot of people up, since they assume that it is due to its use of delegate callback methods. However, actually the parse method doesn't return until all the parsing is finished.

    So while you may have multiple connections going at once, you won't have multiple parsing operations happening unless you've multithreaded it yourself.

    To solve the multiple connections problem, how about instead of having one single NSMutableData you have one per connection? There are a number of ways to do that: you might want to look at answers to the following questions for ideas.