简体   繁体   English

在后台线程中运行NSTimer以在主线程完成时调用方法

[英]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: 我有一个创建NSTimer并在后台线程中运行它的静态方法,如下所示:

+ (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! performSelectorOnMainThread:withObject:waitUntilDone:也适用于类!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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