iOS NSTimer无法正常工作?

Ben*_*der 4 methods nstimer ios ios5

这是我的确切代码,似乎没有用.你能告诉我我做错了什么吗?请注意,refreshTimer已在专用接口中声明.

-(void)viewDidLoad {
refreshTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerTest)      userInfo:nil repeats:YES];

}
-(void)timerTest {
NSLog(@"Timer Worked");
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*lum 16

scheduledTimerWithTimeInterval一试:

NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(myMethod) userInfo:nil repeats:YES];
Run Code Online (Sandbox Code Playgroud)

引用:NSTimer timerWithTimeInterval:不工作

scheduledTimerWithTimeInterval:invocation:repeats:和scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:创建自动添加到a的计时器NSRunLoop,这意味着您不必自己添加它们.将它们添加到一个NSRunLoop是导致它们触发的原因.


bit*_*com 7

有两种选择.

如果使用 timerWithTimeInterval

使用类似的以下.

refreshTimer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(timerHandler) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:refreshTimer forMode:NSRunLoopCommonModes];
Run Code Online (Sandbox Code Playgroud)

也是模式是两个选项.NSDefaultRunLoopModeVSNSRunLoopCommonModes

更多信息.请参阅此文档:RunLoopManagement


如果使用 scheduledTimerWithTimeInterval

使用类似的以下.

refreshTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerHandler) userInfo:nil repeats:YES];
Run Code Online (Sandbox Code Playgroud)

计划的计时器会自动添加到运行循环中.

更多信息.请参阅此文档:计时器编程主题

综上所述

" timerWithTimeInterval"您必须记住将计时器添加到要添加的运行循环中.

" scheduledTimerWithTimeInterval"默认自动创建一个在当前循环中运行的计时器.