[英]How to perform a selector on the main thread with the AppDelegate in a global function, in swift?
我希望AppDelegate在可能的情况下执行选择器,这是我的代码:
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)
}
我已经试过了:(应用崩溃)
AppDelegate.performSelector(onMainThread: #selector(removeSource), with: theContext, waitUntilDone: false)
如何通过全局函数在主线程上执行选择器?
performSelectorOnMainThread:withObject:waitUntilDone:
将消息与常见的运行循环模式一起排队。 根据Apple的“并发编程指南”,主队列将交错队列中的任务与应用程序运行循环中的其他事件。 因此,如果事件队列中还有其他事件要处理,则调度队列中的已排队块可以先运行,即使它们是稍后提交的。
要解决此问题,可以为此使用dispatchQueue:
DispatchQueue.main.async {
UIApplication.shared.delegate.removeSource()
}
您可以通过以下链接阅读有关此内容的更多信息: https : //blackpixel.com/writing/2013/11/performselectoronmainthread-vs-dispatch-async.html
喜欢快速4中的以下方法:
performSelector(onMainThread: #selector(self.removeSource), with: nil, waitUntilDone: false)
@objc func removeSource() {
print("removeSource")
}
除了使用选择器,您还可以将removeSource
的内容removeSource
在DispatchQueue.main.sync
或DispatchQueue.main.async
class func removeSource() {
DispatchQueue.main.sync {
// Your code
}
}
编辑:然后您可以像这样调用您的函数AppDelegate.removeSource()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.