2014-04-12 20 views
3

我以編程方式創建UISearchBar和UISearchDisplayController。視圖控制器是一個UITableViewController。 @interface StockTableViewController() <UISearchDisplayDelegate, UISearchBarDelegate>你可以看到下面的代碼。但是當我在搜索欄中輸入時,shouldReloadTableForSearchString不會被調用,包括其他UISearchDisplayDelegate方法。不調用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; 
} 

回答

11

,因爲您建立UISearchDisplayController作爲一個局部變量,這會導致當viewDidLoad中超出範圍時它被釋放它不工作。因此,爲您的搜索顯示控制器創建一個強大的屬性,然後它應該正常工作(如果您命名屬性searchDisplayController,則會遇到命名衝突,因此請將其稱爲其他名稱)。