导航返回时取消 GCD 异步任务 [英] Cancel GCD async task when navigating back

查看:38
本文介绍了导航返回时取消 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 异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆