简体   繁体   中英

Run NSTimer in background thread to call method on completion in main thread

I have a static method that creates a NSTimer and runs it in the background thread, like so:

+ (void) callInBackgroundThread {
    NSTimer *timer = [NSTimer timerWithTimeInterval:0.2
                                            target:self
                                          selector:@selector(callToMainThread)
                                          userInfo:nil repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

and then i call the main thread upon completion like so:

+ (void) callToMainThread{
    NSTimer *timer = [NSTimer timerWithTimeInterval:0
                                             target:self
                                           selector:@selector(foo1)
                                           userInfo:nil repeats:NO];
   [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}

While this works i feel that this is quite sketchy and I wonder if there is a better way of doing this. I would appreciate suggestions, please note that the methods where are static.

Any help would be appreciated.

Regards

performSelectorOnMainThread:withObject:waitUntilDone: also works for classes!

+ (void) callToMainThread {
   [self performSelectorOnMainThread:@selector(foo1) withObject:nil waitUntilDone:NO];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM