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)
複製代碼