如何使用全局函数中的AppDelegate快速在主线程上执行选择器? [英] How to perform a selector on the main thread with the AppDelegate in a global function, in swift?

查看:149
本文介绍了如何使用全局函数中的AppDelegate快速在主线程上执行选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果可能的话,我希望AppDelegate执行选择器,这是我的代码:

I want the AppDelegate to perform the selector if it is possible, here is my code:

func RunLoopSourceScheduleRoutine(info:UnsafeMutableRawPointer?,r1:CFRunLoop?,mode:CFRunLoopMode?)->Void{

    let obj :  RunLoopSource = Unmanaged<RunLoopSource>.fromOpaque(info!).takeUnretainedValue()
    let theContext = RunLoopContext.init(initWithSource: obj, andLoop: r1!)

    let del = UIApplication.shared.delegate

    del.performSelector(onMainThread: #selector(removeSource), with: theContext, waitUntilDone: false)

}  

我已经尝试过:(应用程序崩溃)

I've tried this :(The App crashes)

 AppDelegate.performSelector(onMainThread: #selector(removeSource), with: theContext, waitUntilDone: false)

如何通过全局函数在主线程上执行选择器?

How to perform a selector on the main thread from a global function?

推荐答案

performSelectorOnMainThread:withObject:waitUntilDone:将消息与常见的运行循环模式一起排队.根据Apple的并发编程指南",主队列将交错队列中的任务与应用程序运行循环中的其他事件.因此,如果事件队列中还有其他事件要处理,则调度队列中排队的块可能会先运行,即使它们是稍后提交的.

performSelectorOnMainThread:withObject:waitUntilDone: queues the message with common run loop modes. According to Apple's "Concurrency Programming Guide", the main queue will interleave queued tasks with other events from the app's run loop. Thus, if there are other events to be processed in the event queue, the queued blocks in the dispatch queue may be run first, even though they were submitted later.

要解决此问题,可以如下使用dispatchQueue:

To resolve the issue you can use dispatchQueue for this as follows:

DispatchQueue.main.async {
   UIApplication.shared.delegate.removeSource()
}

您可以在以下链接上了解有关此内容的更多信息: https://blackpixel.com/writing/2013/11/performselectoronmainthread-vs-dispatch-async.html

You can read more about this on following link: https://blackpixel.com/writing/2013/11/performselectoronmainthread-vs-dispatch-async.html

这篇关于如何使用全局函数中的AppDelegate快速在主线程上执行选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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