NSTimer没有开火

Mat*_* S. 10 macos cocoa objective-c nsdate nstimer

我有一个NSTimer,我使用此代码初始化:

testTimer = [[NSTimer alloc] initWithFireDate:[new objectAtIndex:0] interval:0.0 target:self selector:@selector(works:) userInfo:nil repeats:NO];
Run Code Online (Sandbox Code Playgroud)

[new objectAtIndex:0] 是过去的NSDate.

当我启动应用程序时,计时器正在创建,其中fireDate立即生效(因为日期是过去的),但它从不调用我的工作方法.(-(void)works:(id)sender )

谁知道为什么会这样?

Dee*_*olu 18

如果使用initWith..方法创建计时器对象,则必须将其添加到当前运行循环中.

NSRunLoop * theRunLoop = [NSRunLoop currentRunLoop];
[theRunLoop addTimer:testTimer forMode:NSDefaultRunLoopMode];
Run Code Online (Sandbox Code Playgroud)

或者,如果您希望为您设置,请使用scheduled...方法创建计时器.

  • @Matt:应该注意的是,使用`alloc` /`init`意味着你拥有定时器并需要管理它的内存,而`scheduledTimer ...`方法返回你没有拥有的定时器.在任何一种情况下,它都由运行循环保留. (4认同)

Dob*_*ler 15

我刚刚遇到NSTimer的问题.在我的情况下,我没有意识到方法scheduledTimerWithTimeInterval不是多线程安全的.一旦我将计时器移动到主线程,它就开始工作了.

  • 尝试将你的nstimer包装成:dispatch_async(dispatch_get_main_queue(),^ {}); (5认同)