10

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]);
        abort();  // 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?

2
  • sorry about the lack for formatting on the code, i forgot to add the code sample tags
    – gburgoon
    Jun 19, 2009 at 17:20
  • You can edit your post to format the code correctly...
    – CMPalmer
    Jun 19, 2009 at 17:53

4 Answers 4

15

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.

5

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

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

to:

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

1

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...

1
  • 1
    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
    Jun 22, 2009 at 14:43
1

In typical Core Data application one should delete NSF fetchedResultsController:

[NSFetchedResultsController deleteCacheWithName: [self.fetchedResultsController cacheName]];

Or else you'll get an exception (ideally) or you'll have strange behavior.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.