Runloop有效利用空閒時間

d_d發表於2019-01-03

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

相關文章