NSTimer callback on background thread

前端 未结 2 1503
夕颜
夕颜 2021-01-23 22:07

I have a NSTimer defined as follows:

timer = [NSTimer scheduledTimerWithTimeInterval:30
                                         target:self
                


        
2条回答
  •  孤街浪徒
    2021-01-23 22:44

    You are adding the timer to main thread. Your call back will also be in main thread. To schedule the timer in a background thread, I think you need to use NSOperation subclass and schedule the timer to [NSRunLoop currentRunLoop] from inside the operation's main method.

    #import 
    
    @interface BackgroundTimer : NSOperation
    {
        BOOL _done;
    }
    @end
    
    
    
    #import "BackgroundTimer.h"
    
    @implementation BackgroundTimer
    
    -(void) main
    {
        if ([self isCancelled])
        {
            return;
        }
    
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:30
                                                 target:self
                                               selector:@selector(fooBar)
                                               userInfo:nil
                                                repeats:YES];
    
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    
        //keep the runloop going as long as needed
        while (!_done && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                                                  beforeDate:[NSDate distantFuture]]);
    
    }
    
    @end
    

提交回复
热议问题