tags:

views:

2357

answers:

3

So I'm trying to fetch objects from core data. I have list of say 80 objects, and I want to be able to search through them using a UISearchBar. They are displayed in a table.

Using the apple documentation on predicates, I've put the following code in one of the UISearchBar delegate methods.

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
  if (self.searchBar.text !=nil)
  {
    NSPredicate *predicate =[NSPredicate predicateWithFormat:@"name LIKE %@", self.searchBar.text];
    [fetchedResultsController.fetchRequest setPredicate:predicate];
  }
  else
  {
    NSPredicate *predicate =[NSPredicate predicateWithFormat:@"All"];
    [fetchedResultsController.fetchRequest setPredicate:predicate];
  }

  NSError *error = nil;
  if (![[self fetchedResultsController] performFetch:&error]) {
     // Handle error
     NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
     exit(-1);  // Fail
    }  

  [self.tableView reloadData];

    [searchBar resignFirstResponder]; 
    [_shadeView setAlpha:0.0f];
}

If I type in the search field an exact match to the name property of one of those objects, the search works, and it repopulates the table with a single cell with the name of the object. If I don't search the name exact, I end up with no results.

Any Thoughts?

+6  A: 

It seems as though iPhone doesn't like the LIKE operator. I replaced it with 'contains[cd]' and it works the way I want it to.

gburgoon
+1  A: 

Did you try it using MATCH and regular expressions? Just curious to see if LIKE is something that should be avoided on the iPhone or not...

CMPalmer
Ya, match causes an exception to be thrown. Its just odd because apple uses the LIKE operator a lot in their documentation, but it doesn't work the way it says it should.
gburgoon
+2  A: 

use contains[cd] instead of like, and change:

NSPredicate *predicate =[NSPredicate predicateWithFormat:@"All"];

to:

NSPredicate *predicate =[NSPredicate predicateWithFormat:@"1=1"];

greenisus