NSTimer回调在后台线程上 [英] NSTimer callback on background thread
问题描述
我的 NSTimer
定义如下:
timer = [NSTimer scheduledTimerWithTimeInterval:30
target:self
selector:@selector(fooBar)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
我想让它调用回调函数 fooBar
在这种情况下使用后台线程。但当我用检查if([NSThread mainThread])
我总是在主线程上获取它。除了从回调函数调度线程之外还有其他方法吗?
I want it to call the call back function fooBar
in this case using a background thread. But when I check with if ([NSThread mainThread])
i'm always getting it on the main thread. Is there any other way aside from dispatching a thread from the callback function?
推荐答案
您正在将计时器添加到主线程。您的回电也将在主线程中。要在后台线程中安排计时器,我认为您需要使用NSOperation子类并从操作的 main 方法中将计时器安排到[NSRunLoop currentRunLoop]。
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 <Foundation/Foundation.h>
@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
这篇关于NSTimer回调在后台线程上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!