Placing an NSTimer in a separate thread

前端 未结 1 1451
广开言路
广开言路 2020-12-02 19:23

Note: It\'s probably worth scrolling down to read my edit.

I\'m trying to setup an NSTimer in a separate thread so that it continues to fire when us

相关标签:
1条回答
  • 2020-12-02 20:02

    If the only reason you are spawning a new thread is to allow your timer to run while the user is interacting with the UI you can just add it in different runloop modes:

    NSTimer *uiTimer = [NSTimer timerWithTimeInterval:(1.0 / 5.0) target:self selector:@selector(uiTimerFired:) userInfo:nil repeats:YES];      
    [[NSRunLoop mainRunLoop] addTimer:uiTimer forMode:NSRunLoopCommonModes];
    

    As an addendum to this answer it is now possible to schedule timers using Grand Central Dispatch and blocks:

    // Update the UI 5 times per second on the main queue
    // Keep a strong reference to _timer in ARC
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, (1.0 / 5.0) * NSEC_PER_SEC, 0.25 * NSEC_PER_SEC);
    
    dispatch_source_set_event_handler(_timer, ^{
        // Perform a periodic action
    });
    
    // Start the timer
    dispatch_resume(_timer);
    

    Later when the timer is no longer needed:

    dispatch_source_cancel(_timer);
    
    0 讨论(0)
提交回复
热议问题