ios – 未调用UISearchDisplayDelegate方法

我以编程方式创建一个UISearchBar和UISearchdisplayController.视图控制器是一个UITableViewController. @interface StockTableViewController()< UISearchdisplayDelegate,UISearchBarDelegate>你可以看到下面的代码.但是当我在搜索栏中输入时,不会调用shouldReloadTableForSearchString,包括其他UISearchdisplayDelegate方法.

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.searchResults = [NSArray array];

    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.barStyle = UISearchBarStyleDefault;
    searchBar.searchBarStyle = UISearchBarStyleDefault;
    searchBar.showsCancelButton = YES;
    searchBar.showsScopeBar = NO;
    searchBar.delegate = self;

    UISearchdisplayController *searchdisplayController = [[UISearchdisplayController alloc] initWithSearchBar:searchBar contentsController:self];
    searchdisplayController.delegate = self;
    searchdisplayController.searchResultsDataSource = self;
    searchdisplayController.searchResultsDelegate = self;

    self.tableView.tableHeaderView = searchBar;
}

- (void)searchdisplayControllerWillBeginSearch:(UISearchdisplayController *)controller
{
    NSLog(@"searching"); //not showed up in the console
}

- (BOOL)searchdisplayController:(UISearchdisplayController *)controller shouldReloadTableForSearchString:(Nsstring *)searchString
{
    NSLog(@"%@",searchString); //not showed up in the console
    nspredicate *predicate = [nspredicate predicateWithFormat:@"name LIKE %@",searchString];
    NSArray *results = [Stock MR_findAllSortedBy:@"createdDate" ascending:NO withPredicate:predicate];
    if ([results count] > 0) {

        self.searchResults = results;
        [self.searchdisplayController.searchResultsTableView reloadData];
    }
    return YES;
}

解决方法

它不起作用,因为您正在将UISearchdisplayController创建为局部变量,这会导致在viewDidLoad超出范围时将其解除分配.因此,为您的搜索显示控制器创建一个强大的属性,然后它应该正常工作(如果您将属性命名为searchdisplayController,则会遇到命名冲突,因此请将其称为其他内容).

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...