在我的应用程序中,我有一个 UITableViewController。
它的 tableView 分为 3 个部分。
我从我的服务器下载每个部分的数据。为此,我有 3 个函数(例如 f1 f2 和 f3)。每个更新一个相应的 NSArray,用作我的表的数据源。
现在我想要的是使用此函数重新加载数据并在这 3 个函数完成后刷新我的 tableView,但不会打扰用户。
我不熟悉异步请求、 block 、线程等......我正在寻找技巧。
实际上,这就是我所做的:
-(void)viewDidLoad
{
//some settings
[NSTimer scheduledTimerWithTimeInterval:15.0 target:self selector:@selector(reloadDatas) userInfo:nil repeats:YES];
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_async(queue, ^{
[self reloadDatas];
});
}
-(void)reloadDatas
{
dispatch_queue_t concurrentQueue = dispatch_get_main_queue();
dispatch_async(concurrentQueue, ^{
[self f1];
[self f2];
[self f3];
[myDisplayedTable reloadData];
});
}
-(void)f1
{
//load datas with a url request and update array1
}
-(void)f2
{
//load datas with a url request and update array2
}
-(void)f3
{
//load datas with a url request and update array3
}
但是在这里,我的 tableView 一直“卡住”,直到它被刷新。
我不关心 f1 f2 和 f3 的执行顺序,但我需要等待这 3 个函数完成才能刷新我的 tableView。
感谢您的帮助。
编辑
感谢您的所有回答。
这是有效的解决方案:
按照 mros 的建议,我从 viewDidLoad 中删除了调度队列,并替换为 reloadDatas:
dispatch_queue_t concurrentQueue = dispatch_get_main_queue();
与
dispatch_queue_t mainThreadQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
最后,我在主线程中重新加载我的表
dispatch_async(dispatch_get_main_queue(), ^{ [myDisplayedTable reloadData]; });
最佳答案
所以你的“后台线程”实际上是你的主线程。您必须使用 dispatch_get_global_queue 并指定优先级才能实际获得不同的线程。此外,viewDidLoad 中的分派(dispatch)异步是无用的,因为所有 View Controller 生命周期方法都在主线程中调用。我建议在您的 f1、f2 和 f3 方法中执行如下操作:
首先启动异步 url 请求,然后在完成 block 中更新 arrayX 并重新加载 tableview 的特定部分。这样,所有三个请求都可以同时发生,并且表仅在每个请求完成时更新必要的数据。或者,如果您只想重新加载一次,只需将您拥有的 concurrentQueue 变量替换为后台线程,然后在主线程上执行 [tableView reloadData]
。
关于ios - 在后台重新加载 UITableView 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17348132/