2013-12-19 33 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; 
} 
相关问题