NSTimer Reliable Alternatives

前端 未结 2 436
感情败类
感情败类 2020-12-09 20:30

I have an application that is supposed to log certain things every 1 second and I\'m currently using NSTimer, but if my application transitions screens (or almo

2条回答
  •  抹茶落季
    2020-12-09 20:58

    NSTimer is not guaranteed to fire exactly on time, ever. But you can use an NSTimer in a much more reliable way than you are now. When you use scheduledTimerWithTimeInterval you create an NSTimer which is scheduled in the run loop for NSDefaultRunLoopMode. This mode is paused when the UI is being used, so your timers won't fire when there is user interaction. To avoid this pause use the mode NSRunLoopCommonModes. To do this you will have to schedule the timer yourself like so:

    timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(update) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    

提交回复
热议问题