调度不能正常工作
Dispatch doesn't work properly
我尝试在后台获取一些数据并在搜索栏中键入时刷新表格视图,这是我当前的代码:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
Games * game = [[Games alloc] init];
NSArray * temp = [game comingSoonWithPlatform:@"pc" header:[game gameHeader] parseLink:[game gameComingSoonListLinkWithPlatform:@"pc"]];
self.searchArray = [temp valueForKey:@"results"];
[self.tableView reloadData];
});
}
我做错了什么?如果我在搜索栏中再输入一个词,或者如果我点击取消按钮,它会刷新并且数据会出现在表格视图中。
对[self.tableView reloadData];
的调用必须在主线程上。替换行
[self.tableView reloadData];
和
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
您正在从主线程创建后台线程,在进行任何处理后您需要切换到主线程以更新 UI。
例如,您可以在下面的方法中编写代码,如-
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
// [activityIndicator startAnimating];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// do your background code here
Games * game = [[Games alloc] init];
NSArray * temp = [game comingSoonWithPlatform:@"pc" header:[game gameHeader] parseLink:[game gameComingSoonListLinkWithPlatform:@"pc"]];
self.searchArray = [temp valueForKey:@"results"];
dispatch_sync(dispatch_get_main_queue(), ^{
// you are now on the main queue again, update ui here
//[activityIndicator stopAnimating];
[self.tableView reloadData];
});
});
}
我尝试在后台获取一些数据并在搜索栏中键入时刷新表格视图,这是我当前的代码:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
Games * game = [[Games alloc] init];
NSArray * temp = [game comingSoonWithPlatform:@"pc" header:[game gameHeader] parseLink:[game gameComingSoonListLinkWithPlatform:@"pc"]];
self.searchArray = [temp valueForKey:@"results"];
[self.tableView reloadData];
});
}
我做错了什么?如果我在搜索栏中再输入一个词,或者如果我点击取消按钮,它会刷新并且数据会出现在表格视图中。
对[self.tableView reloadData];
的调用必须在主线程上。替换行
[self.tableView reloadData];
和
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
您正在从主线程创建后台线程,在进行任何处理后您需要切换到主线程以更新 UI。
例如,您可以在下面的方法中编写代码,如-
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
// [activityIndicator startAnimating];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// do your background code here
Games * game = [[Games alloc] init];
NSArray * temp = [game comingSoonWithPlatform:@"pc" header:[game gameHeader] parseLink:[game gameComingSoonListLinkWithPlatform:@"pc"]];
self.searchArray = [temp valueForKey:@"results"];
dispatch_sync(dispatch_get_main_queue(), ^{
// you are now on the main queue again, update ui here
//[activityIndicator stopAnimating];
[self.tableView reloadData];
});
});
}