0

I make program with recursion in background thread. To avoid stack overflow I use timer. But I face the problem with Timer + GCD. After fire, timer call function once and stop.

There is small code. I use ARC if it's important.

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
       // Override point for customization after application launch.


      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
     {
          self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerFunction) userInfo:nil repeats:YES];
          [self.timer fire];
     });

     return YES;
 }


 -(void)timerFunction
  {
     NSLog(@"Timer Tick");

  }

What is the problem?

Sorry for my English. Thanks :)

  • 1
    Do you ever add the timer to a runloop? And run that runloop? Why do you need a background thread for the timer to run on? – Wain Dec 20 '13 at 14:17
  • Because I have many functions call itself in background (it's called recursion) and my stack over float after 3000 calls, thats why I make timer: to exit some functions and start it again. But my timer stop with no reason I can understand. – IWantToKnow Dec 20 '13 at 14:23

1 Answers1

1

Don't do what you're trying to do. Just run the timer on the main thread. The timer also needs to be scheduled on a runloop (so use scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: to create it).

Now, if you need to, use dispatch_async in the method called by the time (timerFunction) to perform your processing on a background thread.

Wain
  • 118,658
  • 15
  • 128
  • 151