监听 RunLoop 运行状态
2016-12-03 本文已影响27人
码农淏
CFRunLoopObserverRef CFRunLoopObserverCreateWithHandler(CFAllocatorRef allocator, CFOptionFlags activities, Boolean repeats, CFIndex order, void (^block) (CFRunLoopObserverRef observer, CFRunLoopActivity activity))
参数:
1.CFAllocatorRef allocator //默认值 CFAllocatorGetDefault()
2.CFOptionFlags activities //监听Runloop的什么状态
3.Boolean repeats //是否重复YES/NO
4.CFIndex order //传0
5.Block回调
RunLoop 状态
typedef CF_OPTIONS(CFOptionFlags, CFRunLoopActivity) {
kCFRunLoopEntry = (1UL << 0), //即将进入Runloop
kCFRunLoopBeforeTimers = (1UL << 1), //即将执行Timer
kCFRunLoopBeforeSources = (1UL << 2), //即将处理Sources
kCFRunLoopBeforeWaiting = (1UL << 5), //即将睡眠
kCFRunLoopAfterWaiting = (1UL << 6), //将从睡眠中唤醒
kCFRunLoopExit = (1UL << 7), //即将退出
kCFRunLoopAllActivities = 0x0FFFFFFFU //所有都监听
};
添加Runloop观察者
void CFRunLoopAddObserver(CFRunLoopRef rl, CFRunLoopObserverRef observer, CFStringRef mode);
1.CFRunLoopRef rl //监听的runloop 如 CFRunLoopGetCurrent()
2.CFRunLoopObserverRef observer //观察者
3.CFStringRef mode //Runloop模式
例子:
CFRunLoopObserverRef oberver = CFRunLoopObserverCreateWithHandler(CFAllocatorGetDefault(), kCFRunLoopAllActivities, YES, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
NSLog(@"%zd",activity);
});
CFRunLoopAddObserver(CFRunLoopGetCurrent(), oberver, kCFRunLoopDefaultMode);