How do I create a NSTimer on a background thread?

前端 未结 10 660
感情败类
感情败类 2020-11-28 02:04

I have a task that needs to be performed every 1 second. Currently I have an NSTimer firing repeatedly every 1 sec. How do I have the timer fire in a background thread (no

10条回答
  •  囚心锁ツ
    2020-11-28 02:47

    If you need this so timers still run when you scroll your views (or maps), you need to schedule them on different run loop mode. Replace your current timer:

    [NSTimer scheduledTimerWithTimeInterval:0.5
                                     target:self
                                   selector:@selector(timerFired:)
                                   userInfo:nil repeats:YES];
    

    With this one:

    NSTimer *timer = [NSTimer timerWithTimeInterval:0.5
                                               target:self
                                             selector:@selector(timerFired:)
                                             userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    

    For details, check this blog post: Event tracking stops NSTimer

    EDIT : second block of code, the NSTimer still runs on the main thread, still on the same run loop as the scrollviews. The difference is the run loop mode. Check the blog post for a clear explanation.

提交回复
热议问题