Cancel GCD async task when navigating back(导航返回时取消 GCD 异步任务)
问题描述
我的 iOS 应用程序的视图控制器中有一个运行时间相对较长的任务(5-10 秒).它通过 GCD 在后台异步运行.用户可以在此任务期间进行 UI 操作,因此他也可以按返回按钮导航到上一个视图.
I have a relatively long running task (5-10 secs) in a view controller in my iOS app. It is running async in the background by GCD. The user has the ability to make UI operations during this task, so he also has the ability to press back button to navigate to the previous view.
我的代码很简单:
dispatch_queue_t queue = dispatch_queue_create("com.x.y.z", NULL);
dispatch_async(queue, ^{
TestObject* test = [self getTestObject];
dispatch_async(dispatch_get_main_queue(), ^{
test.resultset.count > 0 ?
[self performSegueWithIdentifier:@"xy" sender:self] :
[UIUtils showSimpleAlert:NSLocalizedString(@"NoDataForInterval",nil)
delegate:self];
});
});
异常信息:由于未捕获的异常NSGenericException
而终止应用程序,原因:
Exception info: Terminating app due to uncaught exception NSGenericException
, reason:
找不到 segue 'xy' 的导航控制器.只有当源控制器由 UINavigationController 的实例管理时,才能使用推送 segue.
Could not find a navigation controller for segue 'xy'. Push segues can only be used when the source controller is managed by an instance of UINavigationController.
所以,问题是,当我的用户返回上一个视图时,GCD 中的任务继续,完成后,我的应用程序崩溃了,因为无法执行我的 segue.
So, the problem is, when my user goes back to the previous view, the task in GCD continues, and when finishing, it crashes my app, because can not perform my segue.
所以,我的问题是:导航到另一个视图时如何取消 GCD 中的 asny 任务?或者只是在完成时以某种方式测试当前视图,例如
So, my question: how can I cancel my asny task in GCD when navigating to another view? Or just simply test somehow the current view when completing, like
if(!self.navigationController)
return;
还是……?
谢谢大家!
推荐答案
if(!self.navigationController)
return;
那你试过了吗?回到主线程后,查看界面状态是完全安全和合理的.
So did you try that? Once you're back on the main thread, it's perfectly safe and reasonable to look around at the state of the interface.
另一方面,如果您真的想在中间轻松取消冗长的任务,请使用 NSOperation 而不是 GCD 块.这为您提供了一个线程安全的取消 API.
If, on the other hand, you really want to make it easy to cancel your lengthy task in the middle, use NSOperation instead of GCD blocks. This gives you a thread-safe cancellation API.
这篇关于导航返回时取消 GCD 异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:导航返回时取消 GCD 异步任务
基础教程推荐
- UINavigationBar 隐藏按钮文本 2022-01-01
- 更改 UITableView 部分标题的颜色 2022-01-01
- 从 UIWebView 访问元数据 2022-01-01
- Android - 如何在runOnUiThread 中将数据传递给Runnable? 2022-01-01
- EditText 中的 setHintTextColor() 2022-01-01
- 在 iOS 7 下 CCMenu 错位 2022-01-01
- 在视图控制器的宽度上水平均匀分布 UIButton 的最简单方法? 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- UINavigationItem 的持久 rightBarButtonItem 属性 2022-01-01
- Firebase 云消息传递令牌未生成 2022-01-01