Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how we can search all records using NSPredicate rather than setting fetchController nil?

I am showing all the records in UITableView easily by using:

if (_fetchedResultsController != nil) {
    return _fetchedResultsController;
}

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
                               entityForName:@"Memo" inManagedObjectContext:[appDelegate managedObjectContext]];
[fetchRequest setEntity:entity];

NSSortDescriptor *sort = [[NSSortDescriptor alloc]
                          initWithKey:@"memodate" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];

NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                    managedObjectContext:[appDelegate managedObjectContext] sectionNameKeyPath:nil
                                               cacheName:nil];
self.fetchedResultsController = theFetchedResultsController;

return _fetchedResultsController;

And for Searching records I am performing this:

- (void)searchBar:(UISearchBar *)aSearchBar textDidChange:(NSString *)searchText {

if (self.searchBar.text ==nil || [self.searchBar.text isEqualToString:@""])
{
    self.fetchedResultsController=nil;
}
else
{
    NSPredicate *predicate =[NSPredicate predicateWithFormat:@"memodesc CONTAINS[cd] %@", self.searchBar.text];
    [_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];}

My Question is what is the right way to search all records if searchText value is nil or ""

I am setting self.fetchedResultsController=nil; again for retrieving all the initial results.

But I don't think so this is the right way. It should be doable with predicate ?

Update:

Its working finw with this predicate

        NSPredicate *predicate =[NSPredicate predicateWithFormat:@"1=1"];
        [_fetchedResultsController.fetchRequest setPredicate:predicate];

But my app is crashing if I used this:

NSPredicate *predicate =[NSPredicate predicateWithFormat:@"All"];
[_fetchedResultsController.fetchRequest setPredicate:predicate];

Unable to parse the format string "ALL"'
like image 401
Tariq Avatar asked Nov 02 '12 10:11

Tariq


1 Answers

And in swift:

let predicate = NSPredicate(value: true)
like image 175
Ben Avatar answered Oct 20 '22 03:10

Ben