这是我的确切代码,似乎没有用。你能告诉我我做错了什么吗?请注意,refreshTimer已在私有接口中声明。
-(void)viewDidLoad {
refreshTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerTest) userInfo:nil repeats:YES];
}
-(void)timerTest {
NSLog(@"Timer Worked");
}
答案 0 :(得分:16)
尝试scheduledTimerWithTimeInterval
:
NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(myMethod) userInfo:nil repeats:YES];
引用:NSTimer timerWithTimeInterval: not working
scheduledTimerWithTimeInterval:invocation:repeats
:和scheduledTimerWithTimeInterval:target:selector:userInfo:repeats
:创建自动添加到NSRunLoop
的计时器,这意味着您不必自行添加它们。将它们添加到NSRunLoop
是导致它们触发的原因。
答案 1 :(得分:7)
有两个选项。
如果使用timerWithTimeInterval
使用类似的以下内容。
refreshTimer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(timerHandler) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:refreshTimer forMode:NSRunLoopCommonModes];
也是模式是双选项。 NSDefaultRunLoopMode
vs NSRunLoopCommonModes
更多信息。请参阅此文档:RunLoopManagement
如果使用scheduledTimerWithTimeInterval
使用类似的以下内容。
refreshTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerHandler) userInfo:nil repeats:YES];
计划的计时器会自动添加到运行循环中。
更多信息。请参阅此文档:Timer Programming Topics
你必须记住“
timerWithTimeInterval
” 将计时器添加到要添加的运行循环中。“
scheduledTimerWithTimeInterval
”默认自动创建一个运行的计时器 当前循环。