3. 再谈 timer 之 CFRunLoopTimerRef
[self performSelectorInBackground:@selector(createTimerInOtherThread) withObject:nil];- (void)createTimerInOtherThread
{
CFAllocatorRef allocator = kCFAllocatorDefault;
CFAbsoluteTime fireDate = CFAbsoluteTimeGetCurrent();
CFTimeInterval interval = 2.0;
CFOptionFlags flag = 0;
CFIndex index = 0;
// 定时器的回调
CFRunLoopTimerCallBack callback = lefexTimerAction;
// 定时器上下文
CFRunLoopTimerContext context = {0, (__bridge void *)(self), NULL, NULL, NULL};
// 创建定时器
CFRunLoopTimerRef timer = CFRunLoopTimerCreate(allocator, fireDate, interval, flag, index, callback, &context);
// 获取当前线程的 runlopp,并且开启 runLoop 定时器才能正常执行
threadRunloop = CFRunLoopGetCurrent();
currentThread = [NSThread currentThread];
// 把timer添加到runloop中,timer将会跑起来
CFRunLoopAddTimer(threadRunloop, timer, kCFRunLoopCommonModes);
// 在 run 之后的代码将不会执行
CFRunLoopRun();
// 下面这行打印将在停止 runLoop 后执行。
NSLog(@"runLoop stop");
}Last updated
Was this helpful?