我想使用 BackGround thread
运行 NSTimer
因为我已经写了下面的代码但是我的 NSTimer
方法没有被调用!
有人能帮帮我吗
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSOperationQueue* operationQueue = [[NSOperationQueue alloc] init];
[operationQueue addOperationWithBlock:^{
// Perform long-running tasks without blocking main thread
[NSTimer scheduledTimerWithTimeInterval:2
target:self
selector:@selector(targetMethod)
userInfo:nil
repeats:YES];
}];
}
-(void)targetMethod{
NSLog(@"Timer Called");
}
最佳答案
您可以为后台线程使用 GCD 调度队列 :=
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)
{
NSTimer *timer = [NSTimer timerWithTimeInterval:0.5
target:self
selector:@selector(timerFired)
userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
dispatch_async(dispatch_get_main_queue(), ^(void)
{
});
});
关于ios - 如何在后台线程中运行 NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41483550/