首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用CFRunLoop的NSTimer

使用CFRunLoop的NSTimer
EN

Stack Overflow用户
提问于 2011-07-14 05:13:25
回答 2查看 1.1K关注 0票数 2

我有一个奇怪的问题。我的NSTimer CallMe方法在没有CFRunLoop的情况下不会触发。如果我添加了CFRunLoop,那么CFRunLoop后面的那行永远不会被调用。我希望CFRunLoop和CallMe方法之后的代码行都被解雇。

编辑-我不关心CFRunLoop,只希望计时器每20秒触发一次。

我已经添加了下面的代码和注释

代码语言:javascript
复制
int main(int argc, char * const argv[]) {
Updater *theUpdater = [[Updater alloc] init];
NSTimer *theTimer = [theUpdater getTimer];
[theTimer retain];
//CFRunLoopRun();
 NSLog(@"I am here"); //If I uncomment CFRUnLoop this line does not get executed
}

@实现更新器

代码语言:javascript
复制
- (NSTimer *)getTimer {
NSLog(@"Timer started");
NSTimer *theTimer;
theTimer = [NSTimer scheduledTimerWithTimeInterval:20.0
                                                target:self 
                                      selector:@selector(CallMe:) 
                                         userInfo:nil 
                                         repeats:YES];

return theTimer;

}

代码语言:javascript
复制
-(void) CallMe:(NSTimer*)theTimer{
NSLog(@"I Never get called");
}

@end

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-07-14 05:37:17

您的计时器需要在CFRunLoop的上下文中创建。所以你的代码应该看起来像这样:

代码语言:javascript
复制
NSRunLoop* myRunLoop = [NSRunLoop currentRunLoop];

Updater * theUpdater = [[Updater alloc] init];

[myRunLoop run]

您应该让Updater对象保留您的计时器,因为它是它的所有者。请注意,当您调用run函数时,它永远不会终止。有关其他选项,请参阅NSRunLoop文档。

票数 1
EN

Stack Overflow用户

发布于 2011-07-14 05:29:04

这是预期的行为。从CFRunLoop文档(增加了重点):

CFRunLoopRun

以默认模式无限期运行当前线程的CFRunLoop对象。

换句话说,除非您在某个地方调用CFRunLoopStop(),否则CFRunLoopRun()永远不会返回。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6685750

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档