Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何立即触发NSTimer?_Ios_Nstimer - Fatal编程技术网

Ios 如何立即触发NSTimer?

Ios 如何立即触发NSTimer?,ios,nstimer,Ios,Nstimer,我需要在我的应用程序启动时调用一个方法,然后每隔5秒调用同一个方法 我的代码非常简单: // Call the method right away [self updatestuff:nil] // Set up a timer so the method is called every 5 seconds timer = [NSTimer scheduledTimerWithTimeInterval: 5

我需要在我的应用程序启动时调用一个方法,然后每隔5秒调用同一个方法

我的代码非常简单:

// Call the method right away
[self updatestuff:nil]

// Set up a timer  so the method is called every 5 seconds
timer = [NSTimer scheduledTimerWithTimeInterval: 5
                                          target: self
                                        selector: @selector(updatestuff:)      
                                        userInfo: nil
                                         repeats: YES];

计时器是否有一个选项,可以立即触发,然后每5秒触发一次?

NSTimer
-fire
[timer fire]是您要查找的内容


这将触发/立即调用计时器,消除时间延迟。

您不能在同一行代码中安排计时器并立即触发事件。所以你必须用两行代码来完成

首先,安排计时器,然后立即在计时器上调用“fire”:

timer = [NSTimer scheduledTimerWithTimeInterval: 5
                                      target: self
                                    selector: @selector(updatestuff:)      
                                    userInfo: nil
                                     repeats: YES];
[timer fire];

调用fire时,计时器等待触发的时间间隔将重置,因为它刚刚运行,然后将以指定的时间间隔继续运行—在本例中,每5秒一次。

您可以初始化计时器并在同一行中触发它:

[(checkStatusTimer = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(checkStatusTimerTick:) userInfo:nil repeats:YES]) fire];
迅速:

timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(foo), userInfo: nil, repeats: true)
timer.fire()

在swift中,这可以通过以下一行实现:

Timer.scheduledTimer(withTimeInterval: intervalInSec, repeats: true) { 
}