NSTimer does not start selector when added using schedTimerWithTimeInterval

I have a piece of code, for example:

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

When I call it like this, the selector does not start after the specified OutInSeconds time. However, if I change it as shown below, 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]; 

Can anyone suggest any suggestions that I'm probably wrong?

I use Xcode 5.1 and build on 7.1.1 iPhone 4S

+7
ios nstimer
source share
2 answers

Call this timer in the main thread:

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

You have 3 options for creating a timer, as Apple claims in the document:

  • Use scheduledTimerWithTimeInterval:invocation:repeats: or scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: class the timer creation method and its schedule in the current run loop in default mode.
  • Use timerWithTimeInterval:invocation:repeats : or timerWithTimeInterval:target:selector:userInfo:repeats: a class method to create a timer object without scheduling it in a run loop. (After creating it, you must add the timer to the run loop manually by calling the addTimer: forMode: method of the corresponding NSRunLoop object.)
  • Highlight a timer and initialize it using initWithFireDate:interval:target:selector:userInfo:repeats: (After creating it, you must add a timer to the start loop by manually calling the addTimer: forMode: method of the corresponding NSRunLoop object.)

The method you use has already scheduled a timer in the current loop, and you should not schedule another time. In my opinion, the problem is in another place, try (to make it easier) to put a fixed value instead of timeOutInSeconds .
Also the most common way to call something after a certain delay (which should not be repeated) is to use dispatch_after:

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

Where 2 is an arbitrary interval (in this case 2 seconds).

+1
source share

All Articles