2013-12-19 32 views
0

我有一個應該在搜索欄中輸入數據時將數據加載到單元格的搜索欄的tableview。我的代碼確實使用帶回調的函數加載數據。將數據打印到控制檯將顯示正確的搜索結果,但在調用reloadData方法後,單元格不會刷新。當另一個字符被鍵入並加載新數據時,tableview將刷新前一個請求的數據。Tableview只在第二次調用後用新數據重新加載

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return _teams.count; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"TeamCell"; 
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 

    TeamModel *team = _teams[indexPath.row]; 
    cell.textLabel.text = team.name; 

    return cell; 
} 

- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText { 
    NSLog(@"%@", searchText); 

    poolDataHandler = [[PoolDataHandler alloc] init]; 
    [poolDataHandler GetTeams:searchText completion:^(NSArray *tempteams) { 
     _teams = tempteams; 
     NSLog(@"%@", _teams); 
     [self.tableView reloadData]; 
    }]; 
} 

請注意,我使用模型類來解析JSON結果。

此外,行計數似乎更新,因爲當結果小於先前的查詢時,它會崩潰。任何想法都將不勝感激!

更新: 當我取消搜索它會刷新與初始結果。我必須缺少一些基本的東西...

+0

調用完成塊的線程是什麼? – Wain

+0

我認爲表重新加載應該在塊之外,因爲在每個字符輸入/ ou這個方法被調用來更新您的數組 – Retro

+0

它從服務器請求數據,所以它被稱爲異步如果這回答你的問題 – Tumtum

回答

0

傻我,我不知道搜索欄和搜索顯示有它自己的tableview ...以下工作對我來說,使用默認的重載功能,將其設置爲不立即重新加載,然後手動在回調中重新加載正確的tableview:

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller   shouldReloadTableForSearchString:(NSString *)searchText { 
    poolDataHandler = [[PoolDataHandler alloc] init]; 
    [poolDataHandler GetTeams:searchText completion:^(NSArray *tempteams) { 
     _teams = tempteams; 
     [self.searchDisplayController.searchResultsTableView reloadData]; 
    }]; 

    return NO; 
} 
相關問題