gpt4 book ai didi

ios - 如何在后台线程中运行 NSTimer

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:34:37 26 4
gpt4 key购买 nike

我想使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com