NSTimer not firing selector when added with scheduledTimerWithTimeInterval

xceph picture xceph · May 12, 2014 · Viewed 9.3k times · Source

I have a code snippet like this:

m_timer = [NSTimer scheduledTimerWithTimeInterval:timeOutInSeconds
                                                       target:self
                                                     selector:@selector(activityIndicatorTimer:)
                                                     userInfo:nil
                                                      repeats:NO];

When I call it like so the selector is not fired after the given timeOutInSeconds. However, if I modify it to be like the following, then the selector is called twice.

NSLog(@"Timer set");
m_timer = [NSTimer scheduledTimerWithTimeInterval:timeOutInSeconds
                                               target:self
                                             selector:@selector(activityIndicatorTimer:)
                                             userInfo:nil
                                              repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:m_timer forMode:NSRunLoopCommonModes];

Could anyone offer any suggestion as to what I am likely doing wrong?

I am using XCode 5.1, and building on 7.1.1 iPhone 4S

Answer

nmh picture nmh · May 13, 2014

Call this timer in main thread:

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