Runloop
可被监听的状态是由CFRunLoopActivity
结构体提供的:bash
public static var entry: CFRunLoopActivity { get }
public static var beforeTimers: CFRunLoopActivity { get }
public static var beforeSources: CFRunLoopActivity { get }
public static var beforeWaiting: CFRunLoopActivity { get }
public static var afterWaiting: CFRunLoopActivity { get }
public static var exit: CFRunLoopActivity { get }
public static var allActivities: CFRunLoopActivity { get }
复制代码
let flags = CFRunLoopActivity.beforeWaiting
let runloopObserVer = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, flags.rawValue, true, 0) { (observer, activity) in
self.perform(#selector(self.doSomething), with: nil, afterDelay: 0.01, inModes: [RunLoop.Mode.default])
}
CFRunLoopAddObserver(CFRunLoopGetCurrent(), runloopObserVer, CFRunLoopMode.defaultMode)
复制代码
这样在beforeWaiting
时会被监听到而后执行操做。因为执行操做又会唤醒Runloop
这样就会进入一个循环所以须要在适当的时候移除掉监听:oop
CFRunLoopRemoveObserver(CFRunLoopGetCurrent(), runloopObserVer, CFRunLoopMode.defaultMode)
复制代码