问题来源
首先来看一段代码,然后猜测输出结果,注意输出内容的顺序:
class Dog: NSObject {
@objc
func getDogName() {
debugPrint("ハチ公")
}
}
var runloop: CFRunLoop!
let sem = DispatchSemaphore(value: 0)
let thread = Thread {
RunLoop.current.add(NSMachPort(), forMode: .common)
runloop = CFRunLoopGetCurrent()
sem.signal()
CFRunLoopRun()
}
thread.start()
sem.wait()
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
CFRunLoopPerformBlock(runloop, CFRunLoopMode.defaultMode.rawValue) {
debugPrint("2")
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
debugPrint("1")
let dog = Dog()
dog.perform(#selector(dog.getDogName), with: nil)
})
}
RunLoop.current.run()
输出结果为1、ハチ公。
原因分析
为什么没有输出2
我们其实已经将block任务加到了thread对应的runloop中了,但是此时的runloop已经处于休眠状态,一直没有被唤醒,所以block內任务一直得不到执行。
如何执行到block內方法
要想执行到block內方法我们需要唤醒runloop,可以使用
let dog = Dog()
dog.perform(#selector(dog.getDogName), with: nil)
CFRunLoopWakeUp(runloop)
这样runloop被唤醒,block方法得到了执行,输出结果为1、ハチ公、2。
添加timer的方式
唤醒runloop的方式有多种,有一张图描述的很不错:
timer的方式,唤醒runloop:
let dog = Dog()
dog.perform(#selector(dog.getDogName), on: thread, with: nil, waitUntilDone: false)
这个方法会在指定线程添加一个定时器,然后执行相应方法。这样通过添加定时器方法成功唤醒runloop,又因为block添加到任务队列较早所以输出顺序是1、2、ハチ公。
关于perform的几个方法
public func perform(_ aSelector: Selector!) -> Unmanaged<AnyObject>!
这个方法是NSObjectProtocol內的方法,会在当前线程通过消息发送机制调用方法。
open func perform(_ aSelector: Selector, on thr: Thread, with arg: Any?, waitUntilDone wait: Bool)
这个方法是NSObject在Thread文件下的一个extension,他可以指定线程并且添加一个timer去执行这个任务,这就是为什么可以唤醒runloop的原因。waitUntilDone这个参数可以设置是否等到selector方法执行完毕后,执行后面的代码。
open func perform(_ aSelector: Selector, with anArgument: Any?, afterDelay delay: TimeInterval)
这个方法是NSObject在Runloop文件下的一个extension。与上一个方法类似,只不过默认执行在当前线程。并且可以设定delay时间。
修改runloop
如果我们将代码改为:
let thread = Thread {
// RunLoop.current.add(NSMachPort(), forMode: .common)
runloop = CFRunLoopGetCurrent()
sem.signal()
CFRunLoopRun()
}
let dog = Dog()
dog.perform(#selector(dog.getDogName), on: thread, with: nil, waitUntilDone: false)
这样只会打印1。因为虽然我们获取到了当前线程的runloop,但是由于runloop没有添加timer或source,所以会马上释放掉,这样线程也被释放掉了,所以再去操作这个线程就得不到任何结果了。