gpt4 book ai didi

ios - 无法在 iOS 应用程序中使用 dispatch_source_t 在 GCD block 中运行计时器

转载 作者:技术小花猫 更新时间:2023-10-29 10:42:46 25 4
gpt4 key购买 nike

我想在 GCD block 中创建一个计时器(每 2 秒触发一次并调用一个方法)以将其用作后台任务。但正如我所见,计时器永远不会触发。这是我的代码:

- (void)startMessaging
{
BOOL queue = YES;
dispatch_queue_t _queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0, _queue);
dispatch_source_set_timer(timerSource, dispatch_walltime(NULL, 0), 2ull * NSEC_PER_SEC,1ull * NSEC_PER_SEC );
dispatch_source_set_event_handler(timerSource, ^{
if (queue) {
[self observeNewMsgs];
}
});
dispatch_resume(timerSource);
}

- (void)observeNewMsgs
{
NSLog(@"JUST TO TEST");
// Staff code...
}

那么这有什么问题呢?我该如何解决这个问题?

最佳答案

你必须让你的 dispatch_source_t 成为一个类属性或实例变量,这样它就不会超出范围(因为在 ARC 中,当它超出范围时,它就会被释放)。如果这样做,您的代码将正常工作,例如:

@interface ViewController ()
@property (nonatomic, strong) dispatch_source_t timerSource;
@property (getter = isObservingMessages) BOOL observingMessages;
@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];

[self startMessaging];
}

- (void)startMessaging
{
self.observingMessages = YES;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
self.timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(self.timerSource, dispatch_walltime(NULL, 0), 2ull * NSEC_PER_SEC, 1ull * NSEC_PER_SEC);
dispatch_source_set_event_handler(self.timerSource, ^{
if (self.isObservingMessages) {
[self observeNewMsgs];
}
});
dispatch_resume(self.timerSource);
}

- (void)observeNewMsgs
{
NSLog(@"JUST TO TEST");
// Staff code...
}

@end

另请注意,如果您希望能够在后台进程启动后更改 BOOL 的值,您可能也希望将其设为类属性,如上所示。我还将它重命名为 observingMessages 以使其目的更加明确。

(这只是文体,但我只对类实例变量使用下划线字符,所以我将你的 _queue 变量重命名为 queue。)

关于ios - 无法在 iOS 应用程序中使用 dispatch_source_t 在 GCD block 中运行计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14589762/

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