iOS计时器循环,每X分钟执行特定操作

3

我想每隔x段时间执行一段特定的代码块,但似乎只是在那段时间内执行了它。以下是我的代码块:

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

}

任何想法如何做到这一点?
2个回答

4
尝试这个:(它将每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方法中编写您想要执行的代码。希望这可以帮到您.. :)


4

这段代码是一个无限循环,每次迭代都会创建一个NSTimer

去掉while循环,这样[self timerHandle]将在间隔时间x内由单个后台线程/定时器调用。苹果有关NSTimer用法的指南(包括如何正确停止定时任务)见此处


是的。您还需要一种停止计时器的方法。 - Owen Hartnett
谢谢,我想这就可以了。我会查看指南来停止程序。 - Oscar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接