我正在使用以下代码使用uisearchbar,tableview和JSON Web服务进行搜索。目前的问题是,虽然应用程序正在搜索并在tableview中显示数据,但是在搜索栏中发生每个文本更改后,它都会进行搜索。我希望它只在用户触摸搜索按钮后进行搜索。当它在uisearch文本字段中的每次更改中查询Web时,它似乎陷入困境。
这是我在寻找的方式:
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
NSString *searchQuery = [NSString stringWithFormat:@"http://api.****/%@",searchText];
NSString *jsonString = [NSString
stringWithContentsOfURL:[NSURL URLWithString:searchQuery]
encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding
error:nil];
NSMutableArray *itemsTMP = [[NSMutableArray alloc] init];
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *results = [parser objectWithString:jsonString error:nil];
itemsTMP = [results objectForKey:@"results"];
// [self setDisplayItems:[results objectForKey:@"results"]];
[self setAllItems:[itemsTMP copy]];
self.displayItems = [itemsTMP copy];
int a = [displayItems count];
NSString *countString = [NSString stringWithFormat:@"results %d",a];
countLabel.text = countString;
[self.tableView reloadData];
}
我想也许代码应该移到
-(void) searchBarSearchButtonClicked:(UISearchBar *)aSearchBar {
[self.searchBar resignFirstResponder];
return;
// searchBar resigns after search clicked
}
但不确定如何将:(NSString *)searchText
添加到此方法
感谢您的帮助
答案 0 :(得分:1)
只需将textDidChange
代码转换为searchBarSearchButtonClicked
方法即可解决您的问题。
-(void) searchBarSearchButtonClicked:(UISearchBar *)aSearchBar {
[self.searchBar resignFirstResponder];
NSString *searchQuery = [NSString stringWithFormat:@"http://api.****/%@",aSearchBar.text];
NSString *jsonString = [NSString
stringWithContentsOfURL:[NSURL URLWithString:searchQuery]
encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding
error:nil];
NSMutableArray *itemsTMP = [[NSMutableArray alloc] init];
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *results = [parser objectWithString:jsonString error:nil];
itemsTMP = [results objectForKey:@"results"];
// [self setDisplayItems:[results objectForKey:@"results"]];
[self setAllItems:[itemsTMP copy]];
self.displayItems = [itemsTMP copy];
int a = [displayItems count];
NSString *countString = [NSString stringWithFormat:@"results %d",a];
countLabel.text = countString;
[self.tableView reloadData];
return;
// searchBar resigns after search clicked
}