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

查看:77
本文介绍了向后导航时取消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的实例管理时,才可以使用推送选择.

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中的任务继续执行,完成后,由于无法执行我的命令,它使我的应用程序崩溃.

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天全站免登陆