委托后,斯威夫特串行调度模块只完成 [英] Swift Serial Dispatch Block only finish after delegate

查看:91
本文介绍了委托后,斯威夫特串行调度模块只完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个很难解释的。我创建用于处理在我的应用程序的一些工作串行队列。想象一下,我做这样的事情:

this is a hard one to explain. I am creating a serial queue for handling some work in my app. Imagine that i do something like this:

dispatch_async(myQueue, { () -> Void in
            self.SendSMS();
            });

dispatch_async(myQueue, { () -> Void in
            self.SendEmail();
            });

现在我想这样做是为了只调用一个委托(SendSMS代表)后self.SendEmail什么完成其工作。

Now what i would like to do is to only call the self.SendEmail after a delegate(SendSMS delegate) finishes its work.

有没有一种简单的方法来做到这一点?

Is there a simple way to do this?

非常感谢

推荐答案

假设 SendSMS 是一个异步方法,我建议改变 SendSMS 来取完成处理程序结束:

Assuming that SendSMS is an asynchronous method, I'd advise changing SendSMS to take a completion handler closure:

// define property to hold closure

var smsCompletionHandler: (()->())?

// when you initiate the process, squirrel away the completion handler

func sendSMSWithCompletion(completion: (()->())?) {
    smsCompletionHandler = completion

    // initiate SMS
}

// when the SMS delegate method is called, call that completion closure

func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {
    // do whatever you want when done

    // finally, call completion handler and then release it

    smsCompletionHandler?()
    smsCompletionHandler = nil
}

因此​​,你会打电话来它像这样,把 sendEmail 完成闭包 sendSMS

self.sendSMSWithCompletion() {
    self.sendEmail()
}

我不知道你的 sendSMS sendEmail 在做什么,但如果你调用 MessageUI 框架,你通常做的主队列中。但是,如果你真的需要做上述的专用队列,然后随意派遣有它。但希望这说明了这一概念:(1)供应完成处理关闭; (二)保存它让你的委托可以调用它; (三)当委托调用,使用封闭性,然后重新设置。

I don't know what your sendSMS and sendEmail are doing, but if you're calling the MessageUI framework, you'd generally do that on the main queue. But if you really need to do the above on your dedicated queue, then feel free to dispatch it there. But hopefully this illustrates the concept: (a) supply completion handler closure; (b) save it so your delegate can call it; and (c) when delegate is called, use that closure property and then reset it.

这篇关于委托后,斯威夫特串行调度模块只完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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