我有一个奇怪的问题。我的NSTimer CallMe方法在没有CFRunLoop的情况下不会触发。如果我添加了CFRunLoop,那么CFRunLoop后面的那行永远不会被调用。我希望CFRunLoop和CallMe方法之后的代码行都被解雇。
编辑-我不关心CFRunLoop,只希望计时器每20秒触发一次。
我已经添加了下面的代码和注释
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
}@实现更新器
- (NSTimer *)getTimer {
NSLog(@"Timer started");
NSTimer *theTimer;
theTimer = [NSTimer scheduledTimerWithTimeInterval:20.0
target:self
selector:@selector(CallMe:)
userInfo:nil
repeats:YES];
return theTimer;}
-(void) CallMe:(NSTimer*)theTimer{
NSLog(@"I Never get called");
}@end
发布于 2011-07-14 05:37:17
您的计时器需要在CFRunLoop的上下文中创建。所以你的代码应该看起来像这样:
NSRunLoop* myRunLoop = [NSRunLoop currentRunLoop];
Updater * theUpdater = [[Updater alloc] init];
[myRunLoop run]您应该让Updater对象保留您的计时器,因为它是它的所有者。请注意,当您调用run函数时,它永远不会终止。有关其他选项,请参阅NSRunLoop文档。
发布于 2011-07-14 05:29:04
这是预期的行为。从CFRunLoop文档(增加了重点):
CFRunLoopRun
以默认模式无限期运行当前线程的CFRunLoop对象。
换句话说,除非您在某个地方调用CFRunLoopStop(),否则CFRunLoopRun()永远不会返回。
https://stackoverflow.com/questions/6685750
复制相似问题