我通过以下方法轻松地在UITableView
中显示所有记录:
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;
而在搜索记录方面,我正在执行以下操作:
- (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];}
我的问题是,如果searchText的值为nil
或""
,搜索所有记录的正确方法是什么?
我正在设置self.fetchedResultsController=nil;
以重新检索所有初始结果。
但我认为这不是正确的方法。应该可以用谓词来做到吗?
更新:
使用以下谓词可以正常工作:
NSPredicate *predicate =[NSPredicate predicateWithFormat:@"1=1"];
[_fetchedResultsController.fetchRequest setPredicate:predicate];
但是如果我使用这个,我的应用程序会崩溃:
NSPredicate *predicate =[NSPredicate predicateWithFormat:@"All"];
[_fetchedResultsController.fetchRequest setPredicate:predicate];
Unable to parse the format string "ALL"'