Runloop可被監聽的狀態
Runloop
可被監聽的狀態是由CFRunLoopActivity
結構體提供的:
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 }
複製程式碼
利用Runloop空閒執行操作
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
這樣就會進入一個迴圈因此需要在適當的時候移除掉監聽:
CFRunLoopRemoveObserver(CFRunLoopGetCurrent(), runloopObserVer, CFRunLoopMode.defaultMode)
複製程式碼