Ios 添加scheduledTimerWithTimeInterval时,NSTimer未触发选择器

Ios 添加scheduledTimerWithTimeInterval时,NSTimer未触发选择器,ios,nstimer,Ios,Nstimer,我有这样一个代码片段: m_timer = [NSTimer scheduledTimerWithTimeInterval:timeOutInSeconds target:self selector:@selector(activityIndicatorTimer:)

我有这样一个代码片段:

m_timer = [NSTimer scheduledTimerWithTimeInterval:timeOutInSeconds
                                                       target:self
                                                     selector:@selector(activityIndicatorTimer:)
                                                     userInfo:nil
                                                      repeats:NO];
当我这样调用它时,选择器在给定的时间秒后不会被触发。但是,如果我将其修改为如下所示,那么将调用选择器两次

NSLog(@"Timer set");
m_timer = [NSTimer scheduledTimerWithTimeInterval:timeOutInSeconds
                                               target:self
                                             selector:@selector(activityIndicatorTimer:)
                                             userInfo:nil
                                              repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:m_timer forMode:NSRunLoopCommonModes];
有人能就我可能做错的事情提出建议吗


我使用的是XCode 5.1,以7.1.1版iPhone 4S为基础,正如苹果在文档中所说,在创建计时器方面,您有3个选项:

  • 使用scheduledTimerWithTimeInterval:invocation:repeats:或
    scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
    class 方法创建计时器,并在中的当前运行循环上对其进行调度 默认模式
  • 使用
    计时器WithTimeInterval:invocation:repeats
    :或
    timerWithTimeInterval:target:selector:userInfo:repeats:
    class方法 创建计时器对象而不在运行循环上调度它。(之后 创建计时器时,必须通过调用 对应NSRunLoop对象的addTimer:forMode:method。)
  • 分配计时器并使用
    initWithFireDate:interval:target:selector:userInfo:repeats:
    method。 (创建计时器后,必须手动将计时器添加到运行循环中 调用相应nsrunlop的addTimer:forMode:方法 对象。)
您正在使用的方法已在当前循环上安排计时器,不应安排其他时间。在我看来,问题出在其他地方,请尝试(使其更容易)使用固定值,而不是
timeoutineseconds

另外,在特定延迟(不应重复)后调用某个内容的最常见方法是使用dispatch\u after:

 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //YOUR CODE
    });

其中2是任意间隔(在本例中为2秒)。

在主线程中调用此计时器:

dispatch_async(dispatch_get_main_queue(), ^{
   m_timer = [NSTimer scheduledTimerWithTimeInterval:timeOutInSeconds
                                                   target:self
                                                 selector:@selector(activityIndicatorTimer:)
                                                 userInfo:nil
                                                  repeats:NO];
});

我猜您是从没有运行循环的后台线程生成此计时器(大多数没有)
scheduledTimerWithTimeInterval
必须从具有运行循环的线程(通常是主线程)调用。要按原样将计时器添加到runloop,您应该使用
timerWithTimeInterval…
。在第一个选项之后,请调用
[m\u timer fire]
,谢谢David,我相信您是正确的。在你的帮助下,我似乎找到了问题所在。如果您希望将此作为答案而不是评论提交,我可以接受。xceph您应该将@nmh answer标记为正确,以帮助其他人更快地找到解决方案。这并不能真正回答问题。