Objective c 当应用程序进入后台状态时,如何添加计时器?

Objective c 当应用程序进入后台状态时,如何添加计时器?,objective-c,timer,nsrunloop,Objective C,Timer,Nsrunloop,以下是我迄今为止所尝试的: - (void)applicationWillResignActive:(UIApplication *)application { timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(triggerTimer:) userInfo:nil repeats:FALSE]; NSRunLoop* runLoop = [NSRunLoop currentRun

以下是我迄今为止所尝试的:

- (void)applicationWillResignActive:(UIApplication *)application
{

     timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(triggerTimer:) userInfo:nil repeats:FALSE];
     NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
     [runLoop addTimer:timer forMode:NSRunLoopCommonModes];
     [runLoop run];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    if (timer && [timer isValid]) {
        [timer invalidate];
     }
}
我的问题是,如果我使计时器无效,runloop仍在运行并冻结我的UI(动画不工作,滚动不工作,等等)。你知道我该怎么做吗


提前谢谢

您不应该创建计时器
应用程序willresignactive
。相反,您应该将当前日期/时间保存在
ApplicationIdentinterBackground

// Not sure how you are keeping session information
// You can use a variable to store session id
// or simple keep a bool to indicate session is valid
// In this example, let say I just keep a session BOOL

- (void)applicationDidEnterBackground:(UIApplication *)application {
   // save the save the app enters background
   backgroundTime_ = [NSDate date];        
}

// In this example I am going to check if my session is valid in two stages
// You can do it in one stage if you like
- (void)applicationWillEnterForeground:(UIApplication *)application {
   // I only need to do a time-out check if I have a valid session
   if (isValidSession_ && backgroundTime_)
   {
       // get the number of second since we entered background
       NSTimeInterval span = [backgroundTime_ timeIntervalSinceNow];
       if (span > (15 * 60))
       {
           isValidSession_ = NO;      
       }
   }

}

// This is wheer the magic occurs
- (void)applicationDidBecomeActive:(UIApplication *)application {
    // check if session is still valid
    if (!isValidSession_)
    {
        // Load the login view
    }
}

为什么要在后台设置计时器?你想完成什么?如果应用程序在后台运行超过15分钟,请注销用户,然后再次显示登录屏幕。谢谢,它工作得非常好!我在代码中添加了一个小改动,NSTimeInterval span=[[NSDate date]timeIntervalSinceDate:backgroundTime];所以跨度现在是正的,而不是负的。