I have a UISearchbar in my app. This is a dynamic search and as the user enters text, a remote database is searched via a remote API call (I think it is through REST).
The table view gets refreshed dynamically, as the user types. I am using NSXMLParser for parsing the XML results. (so 3 delegate methods; didStartElement, didEndElement)
In some cases, there are duplicate entries shown in the results
e.g. If user has typed YAH, it shows YAHOO 3-4 times. I'm not sure why.
How can I reduce the number of times the parsing is done, or how to delay the parsing, so that it does not make a request for every character entered/deleted by the user.
This, I am assuming, might fix the problem.
One thing you can do is introduce a delay before you send off the remote API call, instead of sending one query for every character.
// Whenever UISearchbar text changes, schedule a lookup
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)text {
// cancel any scheduled lookup
[NSObject cancelPreviousPerformRequestsWithTarget:self];
// start a new one in 0.3 seconds
[self performSelector:@selector(doRemoteQuery) withObject:nil afterDelay:0.3];
}
Here are the relevant parts of a method I use in one of my apps to remove duplicates from a web service result.
NSMutableArray *mutableResults = [[myResults mutableCopy] autorelease];
NSMutableSet *duplicates = [NSMutableSet set];
NSMutableIndexSet *indexesToRemove = [NSMutableIndexSet indexSet];
for (NSString *result in mutableResults)
{
if (![duplicates containsObject:result])
[duplicates addObject:result];
else
[indexesToRemove addIndex:[mutableResults indexOfObject:object]];
}
[mutableResults removeObjectsAtIndexes:duplicates];
return mutableResults;