gburgoon
gburgoon

Reputation: 601

Querying Core Data with Predicates - iPhone

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?

Upvotes: 10

Views: 11582

Answers (4)

Nick
Nick

Reputation: 1278

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.

Upvotes: 1

greenisus
greenisus

Reputation: 1707

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

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

to:

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

Upvotes: 5

CMPalmer
CMPalmer

Reputation: 8623

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

Upvotes: 1

gburgoon
gburgoon

Reputation: 601

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.

Upvotes: 15

Related Questions