11

我想在 GCD 块中创建一个计时器(它将每 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...
}

那么这有什么问题呢?我怎样才能解决这个问题?

4

1 回答 1

32

您必须创建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。)

于 2013-01-29T19:34:07.113 回答