Runloop有效利用空闲时间

1,947 阅读1分钟

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)