开发者

How to set a target of NSTimer from active instance when applicationDidBecomeActive on iphone

I have an NSTimer that I created in the appDelegate to handle the pause when the app locks or is put in the background, but the timers selector is in another viewController, when the user is in that viewController an开发者_开发知识库d then hits the home button the app closes and moves to the background, but when the app is tapped I need to set the timer again, in the applicationDidBecomeActive, but am not sure how I access the active viewController from the app delegate, I have tried setting the timer in the viewController's viewDidAppear but it is not fired, if anyone has some clues as how to handle this I would be very grateful.


Create a variable to store viewController in the app delegate...

Or if you are using a UINavigationController you can use [navigationController topViewController]


Well it turns out that this is pretty easy, I just wasn't thinking it through, maybe a bit too tired, anyway the answer is close to what David mentioned, the key is to loop through the viewControllers in the navigation controller to get the proper viewController

  for (UIViewController *vc in [self.navigationController viewControllers]) {
    if ([vc isKindOfClass:[CustomViewController class]]) {
      CustomViewController *fvc = (CustomViewController *)vc;
      self.sessionTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:fvc selector:@selector(saveTimesAndUpdateButtonDisplay) userInfo:nil repeats:YES];

      [[NSRunLoop currentRunLoop] addTimer:sessionTimer forMode:NSRunLoopCommonModes]; 
    }
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜