我有一个tableView,它通过UISearchBar的textDidChange函数刷新数组中的数据。数据是正确的,但是在击中一个额外的角色之后它才出现在tableView中(例如,如果我在搜索栏中输入'Boise',没有任何反应,但是'Boise1'将加载两个名为'Boise的城市'..它落后了一步。)
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
//---if there is something to search for---
if ([searchText length] > 0) {
NSLog(@"greater than 0!");
isSearchOn = YES;
canSelectRow = YES;
self.tableView.scrollEnabled = YES;
[self performSelector:@selector(someMethod) withObject:nil afterDelay:0];
//[NSThread detachNewThreadSelector:@selector(matchSearchText)
// toTarget:self withObject:nil];
//[self matchSearchText];
}
else {
//---nothing to search---
isSearchOn = NO;
canSelectRow = NO;
self.tableView.scrollEnabled = NO;
}
}
并在所谓的方法中:
- (void) someMethod {
NSLog(@"-------------");
NSLog(@"some Method whut!");
CityLookup *cityLookup = [[CityLookup alloc] findCity:searchBar.text];
// clear array
[tableCities removeAllObjects];
if ([cityLookup.citiesList count] > 0) {
tableCities = cityLookup.citiesList;
int size = [tableCities count];
NSLog(@"there are %d objects in the array", size);
}
[cityLookup release];
[self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:tableCities waitUntilDone:YES];
}
最后是cellForRowAtIndexPath:
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
int size = [tableCities count];
NSLog(@"there are %d objects in the array NOW", size);
static NSString *kCellID = @"cellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
NSString *cellValue = [tableCities objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
return cell;
}