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?
Fetching Data From CoreData We have created a function fetch() whose return type is array of College(Entity). For fetching the data we just write context. fetch and pass fetchRequest that will generate an exception so we handle it by writing try catch, so we fetched our all the data from CoreData.
Core Data is an object graph and persistence framework provided by Apple in the macOS and iOS operating systems. It was introduced in Mac OS X 10.4 Tiger and iOS with iPhone SDK 3.0. It allows data organized by the relational entity–attribute model to be serialized into XML, binary, or SQLite stores.
The next time you need to store data, you should have a better idea of your options. Core Data is unnecessary for random pieces of unrelated data, but it's a perfect fit for a large, relational data set. The defaults system is ideal for small, random pieces of unrelated data, such as settings or the user's preferences.
Use Core Data to save your application's permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. To sync data across multiple devices in a single iCloud account, Core Data automatically mirrors your schema to a CloudKit container.
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.
use contains[cd] instead of like, and change:
NSPredicate *predicate =[NSPredicate predicateWithFormat:@"All"];
to:
NSPredicate *predicate =[NSPredicate predicateWithFormat:@"1=1"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With