美文网首页
iOS_RunLoop_CFRunLoopObserver

iOS_RunLoop_CFRunLoopObserver

作者: 萧修 | 来源:发表于2023-12-18 17:43 被阅读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)
    

    相关文章

      网友评论

          本文标题:iOS_RunLoop_CFRunLoopObserver

          本文链接:https://www.haomeiwen.com/subject/ijbagdtx.html