我想根据用户键入搜索内容来搜索AppStore。
我已设置以下代码来执行此操作,这将修改对输入的每个字符的搜索以缩小搜索范围。
但是,由于每个输入的字符都有一个请求,这些请求可能需要一段时间才能返回,因此用户界面可能会无法响应。
我想a)了解如何阻止UI变得无法响应(我担心我将运行带回到主线程上,带有performselectoronmainthread?),以及b)是否应谨慎取消之前的查找输入字符,因此使用新的更窄的搜索,如果是,如何做到这一点?
提前致谢。
更新:我已经尝试过Emilie Lessard提出的建议,虽然我可以看到逻辑,但我无法让这个有益于该应用。见下面的回复。
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
jsonResults = nil;
[self.tableView reloadData];
}
else
{
jsonResults = nil;
[self.tableView reloadData];
NSURL *searchUrl = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/search?term=%@&country=gb&entity=software",text]];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:searchUrl];
[self performSelectorOnMainThread:@selector(fetchedData:)
withObject:data waitUntilDone:NO];
});
}
}
-(void)fetchedData:(NSData *)responseData{
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
jsonResults = [json objectForKey:@"results"];
[self.tableView reloadData];
}
答案 0 :(得分:1)
您需要使用dispatch_async()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//Do the computing-research
dispatch_async(dispatch_get_main_queue(), ^{
//do UI update here
});
});
通过使用全局队列,您的应用的UI不会被阻止。一旦计算/接收了所有信息,您回到主线程是强制性的(通过使用dispatch_async(dispatch_get_main_queue())
进行所有UI更新,或者您将最终使用难以调试崩溃。