【问题标题】:How can I have an NSTimer going throughout the entire time the user is in the app?我怎样才能让 NSTimer 在用户在应用程序中的整个时间内运行?
【发布时间】:2013-05-03 06:23:03
【问题描述】:

如何让 NSTimer 贯穿用户在应用中的整个时间?

我希望能够更改视图控制器并执行不同的功能,同时计时器在后台运行。如果计时器达到 0,那么我想触发一个事件。当应用程序在后台时,我还可以在应用程序内部设置一个计时器吗?甚至当 iPhone 的屏幕关闭时?

感谢您的回答!

【问题讨论】:

  • 你可以在 App delegate 中使用 Timer

标签: iphone ios background nstimer background-process


【解决方案1】:

在 Appdelegate 中执行这段代码,使计时器成为它的属性。

self.timer = [NSTimer scheduledTimerWithTimeInterval:intervalForTimer
                                                    target: self
                                                  selector: @selector(timerExpired:)
                                                  userInfo: nil
                                                   repeats: NO];

   //Run the timer on the runloop to ensure that it works when app is in background
  [[NSRunLoop currentRunLoop]addTimer:self.timer forMode: NSDefaultRunLoopMode];

【讨论】:

    【解决方案2】:

    在应用委托中运行此方法

    -(void) timerfunc{
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
        timer = [NSTimer scheduledTimerWithTimeInterval:(0.5) target:self selector:@selector(yourfunction) userInfo:nil repeats:YES ];
        [pool release];
    
    }
    

    【讨论】:

    • 什么时候调用这个方法?
    • - (void)applicationDidFinishLaunching:(UIApplication *)application
    猜你喜欢
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 2016-09-25
    • 2010-12-10
    • 2021-01-18
    相关资源
    最近更新 更多