我有一个 tableView,它通过 UISearchBar 的 textDidChange 函数从数组中刷新数据。数据是正确的,但它直到点击一个附加字符后才会出现在 tableView 中(因此,例如,如果我在搜索栏中输入“博伊西”,则没有任何反应,但“博伊西 1”将加载两个名为“博伊西”的城市'..所以它落后了一步)。
- (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;
}