简体   繁体   English

iphone上的applicationDidBecomeActive时如何从活动实例中设置NSTimer的目标

[英]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 and 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.我有一个我在 appDelegate 中创建的 NSTimer 来处理应用程序锁定或置于后台时的暂停,但计时器选择器位于另一个 viewController 中,当用户在该 viewController 中然后点击主页按钮时应用程序关闭并移动到后台,但是当应用程序被点击时,我需要在 applicationDidBecomeActive 中再次设置计时器,但我不确定如何从应用程序委托访问活动 viewController,我尝试在 viewController 的 viewDidAppear 中设置计时器但是它没有被解雇,如果有人知道如何处理这个问题,我将不胜感激。

Create a variable to store viewController in the app delegate...创建一个变量以将 viewController 存储在应用程序委托中...

Or if you are using a UINavigationController you can use [navigationController topViewController]或者,如果您使用的是 UINavigationController,您可以使用 [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好吧,事实证明这很容易,我只是没有考虑清楚,可能有点太累了,反正答案接近大卫提到的,关键是循环通过导航 controller 中的 viewControllers 得到正确的视图控制器

  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]; 
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM