iOS计时器循环,每隔X分钟执行一个特定的动作



我试图每x次执行一个特定的代码块,但似乎我所做的就是在那段时间执行它。这是我的一段代码

while (TRUE) {
    NSTimer *countDown = [NSTimer
                       scheduledTimerWithTimeInterval:(x)
                       target:self
                       selector:@selector(timerHandle)
                       userInfo:nil
                       repeats:YES];
}

有什么好主意吗?

如上所述,这是一个无限循环,每次循环迭代创建一个NSTimer

试试没有while环路。这将导致[self timerHandle]在间隔x上被单个后台线程/计时器调用。关于NSTimer使用的Apple指南(包括其他人指出的如何正确地停止你的定时任务)在这里。

试试这个:(它将每5秒调用一次executeMethod)

if (![NSThread isMainThread]) {
    dispatch_async(dispatch_get_main_queue(), ^{
        [NSTimer scheduledTimerWithTimeInterval:5.0
                                         target:self
                                       selector:@selector(executeMethod)
                                       userInfo:nil
                                        repeats:YES];
    });
}
else{
    [NSTimer scheduledTimerWithTimeInterval:5.0
                                     target:self
                                   selector:@selector(executeMethod)
                                   userInfo:nil
                                    repeats:YES];
}

executeMethod方法中编写要执行的代码。希望这能帮到你…:)

相关内容

最新更新