iOS:获取NSTimer从现在开始5秒钟触发

问题描述:

情境我正在开发一个应用程序,需要点击按钮5秒后触发一个方法。iOS:获取NSTimer从现在开始5秒钟触发

THE CODE这是假定5秒

NSDate *fiveSecondsFromNow = [[NSDate date] dateByAddingTimeInterval:5.0f]; 
    NSTimeInterval timeInterval = [fiveSecondsFromNow timeIntervalSinceNow]; 

controlTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(controlTimerExpire) userInfo:nil repeats:NO]; 

// I ALSO TRIED THIS; HARDCODING IT LIKE BELOW 

controlTimer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(controlTimerExpire) userInfo:nil repeats:NO]; 

问题controlTimerExpire按钮被点击后立即得到烧成后,以衬托controlTimerExpire方法的代码。按钮水龙头和controlTimerExpire方法点火之间需要5秒。

问题为什么这个立即发射并且从现在开始5秒不发射?

链接我上面所做的正是下面这些链接所要做的事情,但它不会产生与链接中相同的结果。为什么?

Set an NSTimer to fire once in the future

How to call a method every x seconds in Objective-C using NSTimer?

+0

我配得上我的问题。对不起,混在一起的人。 –

+0

顺便说一句 - 为此使用'dispatch_after'将会非常简单。不需要定时器。没有额外的方法需要。 – rmaddy

+0

还没有尝试过,但听起来很有希望。谢谢@rmaddy!你是男人中的神。 –

这个问题实际上在我拨打[controlTimer fire];的代码中进一步下降了。这是遗留下来的,因为我试图让它起作用,并且把它遗忘在那里。哎呀,只是浪费了半个小时。因此,对于你们来说,可能有同样的问题,你需要的是设置

[NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(controlTimerExpire) userInfo:nil repeats:NO];

,你并不需要显式调用fire因为scheduledTimerWithTimeIntervalscheduled部分将火选择你基于你设定的时间间隔。

你的整个NSDate的计算是错误的和不必要的。 NSTimer需要几秒钟。如果你想从现在开始5秒钟,只需通过5