Objective c 从其调用方法中使NSTimer无效

Objective c 从其调用方法中使NSTimer无效,objective-c,ios,multithreading,nstimer,Objective C,Ios,Multithreading,Nstimer,我已经使用[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:]计划了一个计时器,并希望在触发时使其失效 - (id)init { [NSTimer scheduledTimerWithInterval:1 target:self selector:@selector(fired:) userInfo:nil repeats:YES]; } - (void)fired:(NSTimer *)timer {

我已经使用[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];
    }
}
允许这样做吗?文件说明

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


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

可以从激发的方法中使其无效,因为激发的方法位于计时器调度的同一线程上:

scheduledTimerWithTimeInterval:目标:选择器:用户信息:重复:

创建并返回新的NSTimer对象,并以默认模式在当前运行循环中对其进行调度


可以从激发的方法中使其无效,因为激发的方法位于计时器调度的同一线程上:

scheduledTimerWithTimeInterval:目标:选择器:用户信息:重复:

创建并返回新的NSTimer对象,并以默认模式在当前运行循环中对其进行调度


从fire方法中调用
[timer invalidate]
很好,该代码将在创建计时器时使用的线程中执行

你引用的苹果文档只是警告你,如果你创建了一个单独的线程并使它的计时器失效,那么,也只有在那时,才会出现不可预测的行为


从fire方法中调用
[timer invalidate]
很好,该代码将在创建计时器时使用的线程中执行

你引用的苹果文档只是警告你,如果你创建了一个单独的线程并使它的计时器失效,那么,也只有在那时,才会出现不可预测的行为


这是一个比被接受的答案更好的答案。谢谢,这是一个比被接受的答案更好的答案。非常感谢
// 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);