문제

I am trying to execute a certain block of code every x amount of time, but it seems that all I am doing is executing it during that time. Here's a block of my code.

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

}

Any ideas as to how to do it?

도움이 되었습니까?

해결책

As written, this is an infinite loop, creating an NSTimer every loop iteration.

Try it without the while loop. This should cause [self timerHandle] to be invoked on interval x by a single background thread/timer. The Apple guide to NSTimer usage (including as others point out, how to properly stop your timed task) is here.

다른 팁

Try this: (It will call executeMethod on every 5 sec)

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];
}

Write the code you want to be executed in executeMethod method. Hope this helps.. :)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top