JHHK

欢迎来到我的个人网站
行者常至 为者常成

参考:RunLoop(三)

参考书籍 《多线程编程指南》
原著:Apple Inc.
翻译:謝業蘭 【老狼】

目录

配置RunLoop的源

一、定义自定义输入源

二、配置定时源
为了创建一个定时源,你所需要做只是创建一个定时器对象并把它调度到你的 run loop。Cocoa 程序中使用 NSTimer 类来创建一个新的定时器对象,而 Core Foundation 中使用 CFRunLoopTimerRef 不透明类型。本质上,NSTimer 类是 Core Foundation 的简单扩展,它提供了便利的特征,例如能使用相同的方法创建和调配 定时器。

手工创建一个定时器

// Create and schedule the first timer.
   
NSDate* futureDate = [NSDate dateWithTimeIntervalSinceNow:1.0];
   
NSTimer* myTimer = [[NSTimer alloc] initWithFireDate:futureDate
   
                                            interval:0.1
   
                                            target:self
   
                                            selector:@selector(myDoFireTimer1:)
   
                                            userInfo:nil
   
                                            repeats:YES];
   
[myRunLoop addTimer:myTimer forMode:NSDefaultRunLoopMode];

创建定时器并以默认模式把它们添加到当前线程的 run loop

// Create and schedule the second timer.
   
[NSTimer scheduledTimerWithTimeInterval:0.2
   
                                target:self
   
                              selector:@selector(myDoFireTimer2:)
   
                              userInfo:nil
   
                              repeats:YES];

显示了使用 Core Foundation 函数来配置定时器的代码。尽管这个例 子中并没有把任何用户定义的信息作为上下文结构,但是你可以使用这个上下文结构 传递任何你想传递的信息给定时器。关于该上下文结构的内容的详细信息,参阅 CFRunLoopTimer Reference。

CFRunLoopRef runLoop = CFRunLoopGetCurrent();
  
CFRunLoopTimerContext context = {0, NULL, NULL, NULL, NULL};
  
CFRunLoopTimerRef timer = CFRunLoopTimerCreate(kCFAllocatorDefault, 0.1, 0.3, 0, 0, &myCFTimerCallback, &context);
   
CFRunLoopAddTimer(runLoop, timer, kCFRunLoopCommonModes);

三、配置基于端口的输入源


行者常至,为者常成!





R
Valine - A simple comment system based on Leancloud.