views:

216

answers:

2

Hi guys,

I'm trying to implement a better live(search as you type) contact search in my iPhone app. After doing some real device testing if found my current (non-threaded) implementation is just too slow. As far as I know there is no spotlight API for the iPhone. So I think the solution will have to be threaded so that it updates the results every x seconds instead of every keystroke. Are there any open source implementations I could build upon?

Thanks!

A: 

How slow? It seems like there might be simpler optimizations (other than threading) to your search and update functionality, especially given you are simply searching contacts. Unless you have thousands of contacts, I can't imagine this being particularly slow.

Jeff B
It was incredibly slow, I was shocked. I don't have that many contacts on my 3G phone but it slowed down my typing to like one character per second. =(
Hua-Ying
+1  A: 

As far as I know there is no spotlight API for the iPhone.

You don't need one. Here's one way to go about it:

  1. Put your contacts into a Core Data persistent store
  2. Use NSFetchedResultsController to manage a result set
  3. Use UISearchDisplayController to apply an NSPredicate on the result set in real time

The only threading I can see that you would need is a separate thread to populate the Core Data store with contacts.

Once you have a result set via NSFetchedResultsController, it is quite easy to apply a predicate. For example:

if ([self.searchBar.text length]) {
    _predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"(myContactName contains[cd] '%@')", self.searchBar.text]];
    [self.fetchedResultsController.fetchRequest setPredicate:_predicate];
}

NSError *error;
if (![self.fetchedResultsController performFetch:&error]) {
    // handle error...
}
NSLog(@"filtered results: %@", [self.fetchedResultsController fetchedObjects]);

will filter the result set [self.fetchedResultsController fetchedObjects] on the fly.

Alex Reynolds