Runloop 学习之 CFRunloopTimer

本文详细探讨了CFRunloopTimer的定义、回调机制及其实现,包括如何添加和移除timer,以及与NSTimer和CADisplayLink的区别。CFRunloopTimer在内部转化为GCD timer并注册到runloop,确保在指定模式下触发回调。尽管有时间误差容忍度,但错过的时间点不会补回。CADisplayLink提供与屏幕刷新率同步的定时器,适合帧动画,而NSTimer适用于更广泛场景。
摘要由CSDN通过智能技术生成

CFRunloopTimer

CFRunloopTimer 定义
struct __CFRunLoopTimer {
    CFRuntimeBase _base;
    uint16_t _bits;  //标记fire状态
    pthread_mutex_t _lock;
    CFRunLoopRef _runLoop;        //添加该timer的runloop
    CFMutableSetRef _rlModes;     //存放所有 包含该timer的 mode的 modeName,意味着一个timer可能会在多个mode中存在
    CFAbsoluteTime _nextFireDate;
    CFTimeInterval _interval;     //理想时间间隔  /* immutable */
    CFTimeInterval _tolerance;    //时间偏差      /* mutable */
    uint64_t _fireTSR;          /* TSR units */
    CFIndex _order;         /* immutable */
    CFRunLoopTimerCallBack _callout;    /* immutable */
    CFRunLoopTimerContext _context; /* immutable, except invalidation */
};

结论:

  • 一个 timer 只能放在一个 runloop 里
  • 一个 timer 可以放在不同的 mode 里

CFRunloopTimer 和 NSTimer 是 toll-free bridged 的,可以相互转换

timer 回调
__CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__()
CFRunloopTimer 实现
CFRunloopAddTimer
void CFRunLoopAddTimer(CFRunLoopRef rl, CFRunLoopTimerRef rlt, CFStringRef modeName) {    
    CHECK_FOR_FORK();
    if (__CFRunLoopIsDeallocating(rl)) return;
    if (!__CFIsValid(rlt) || (NULL != rlt->_runLoop && rlt->_runLoop !
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值