iOS_RunLoop_CFRunLoopObserver

2023-12-18  本文已影响0人  萧修

CFRunLoopObserver监听者,runloop事件。

public struct CFRunLoopActivity : OptionSet, @unchecked Sendable {

    public init(rawValue: CFOptionFlags)

    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 }
}

entry:即将进入运行循环
beforeTimers:即将处理timers
beforeSources:即将处理sources
beforeWaiting:即将等待,即将进入休眠
afterWaiting:休眠之后,刚从休眠唤醒
exit:退出runloop循环

观察runloop的状态变化

public func CFRunLoopObserverCreateWithHandler(
_ allocator: CFAllocator!,//分配的空间
_ activities: CFOptionFlags, //要监听的状态
_ repeats: Bool, 
_ order: CFIndex, 
_ block: ((CFRunLoopObserver?, CFRunLoopActivity) -> Void)!) 
-> CFRunLoopObserver!
let actitities = CFRunLoopActivity.allActivities //actitities 传入要监听的所有状态
        let allocator =  CFAllocatorGetDefault().takeUnretainedValue()
        let observer =  CFRunLoopObserverCreateWithHandler(allocator, 
                                                           actitities.rawValue,
                                                           true,
                                                           0) { observer, activity in
            switch activity {
            case .entry :
                print("进入runloop循环")
            case .beforeTimers:
                print("即将处理timers")
            case .beforeSources:
                print("即将处理Source")
            case .beforeWaiting:
                print("即将休眠")
            case .afterWaiting:
                print("刚从休眠唤醒")
            case .exit:
                print("runloop循环结束")
            default:
                break
            }
        }
        CFRunLoopAddObserver(runloop, observer, .defaultMode)
上一篇 下一篇

猜你喜欢

热点阅读