1

我已经使用 [NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:] 安排了一个计时器,并希望在它触发时使其无效。

- (id)init
{
    [NSTimer scheduledTimerWithInterval:1 target:self selector:@selector(fired:) userInfo:nil repeats:YES];
}

- (void)fired:(NSTimer *)timer
{
    if (someCondition) {
        [timer invalidate];
    }
}

这是允许的吗?该文件指出

您必须从安装了计时器的线程发送此消息。如果您从另一个线程发送此消息,与计时器关联的输入源可能不会从其运行循环中删除,这可能会阻止线程正确退出。

如果这不是完成此任务的正确方法:正确的方法是什么?

4

2 回答 2

5

从 fire 方法中调用[timer invalidate]就可以了,该代码将在与创建计时器时使用的线程相同的线程中执行。

您引用的 Apple Doc 仅警告您,如果您创建一个单独的线程并从中使计时器无效,那么,并且只有这样,应该预期不可预测的行为。

前任。

// Create the background queue
dispatch_queue_t queue = dispatch_queue_create("do not do this", NULL);

// Start work in new thread
dispatch_async(queue, ^ { 

         // !! do not do this  !!
         if (someCondition) {
                 [yourTimer invalidate];
         }
         // or this
         [self fire:yourTimer];
});

// won’t actually go away until queue is empty
dispatch_release(queue);
于 2012-05-15T10:22:00.623 回答
3

可以从触发的方法中使其无效,因为触发的方法与计时器安排在同一线程上:

scheduleTimerWithTimeInterval:target:selector:userInfo:repeats:

创建并返回一个新的 NSTimer 对象,并以默认模式将其安排在当前运行循环中。

于 2012-05-15T10:15:07.337 回答