Objective-c进入后台时不要暂停

时间:2011-08-29 21:20:52

标签: iphone objective-c multithreading background

是否可以在后台模式下暂停应用程序(当您按下主页按钮并且应用程序最小化时)?我有一些我不想暂停的计时器和变量。

编辑:

我已按照此示例http://evilrockhopper.com/2010/01/iphone-development-keeping-the-ui-responsive-and-a-background-thread-pattern/

我已经调用了一个计时器,但是当我进入后台模式时它没有被调用:

- (void)applicationDidEnterBackground:(UIApplication *)application {
    if(self.viewController.timerquest != NULL)
    {
        if(self.viewController.timerquest.timerRunning){
            // Save varibales
            [self performSelectorInBackground:@selector(performLongTaskInBackground) withObject:nil];
        }
    }
}



- (void) performLongTaskInBackground
{
    // Set up a pool for the background task.
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

    // perform some long task here, say fetching some data over the web.
    //...
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];

    // Always update the components back on the main UI thread.
    [self performSelectorOnMainThread:@selector(completeLongRunningTask) withObject:nil waitUntilDone:YES];

    [pool release];
}

-(void) updateTimer{

    // Update my timer. This method is not being called in background mode
}

我该怎么办?

感谢。

4 个答案:

答案 0 :(得分:2)

答案 1 :(得分:1)

答案 2 :(得分:1)

你可以用延迟的背景通知替换计时器吗?

答案 3 :(得分:1)

根据计时器开火时发生的情况,您希望set up a local notification在计时器发生的同时发射;当计时器呈现供用户操作的东西时,这很有用。至于保存变量,你需要使用-applicationDidEnterBackground:来保存你需要的状态,以便在应用重新启动时加载/生成正确的变量(在应用程序退出之前可能不会发生这种情况重新开始了。)

允许执行长时间运行后台任务的任务类型非常有限,特别适用于GPS和播放音频等内容。其他任何事情都需要逐个任务地决定是否模拟继续运行(例如将计时器转到本地通知),暂停并保存必要的状态以在下次运行应用程序时继续,只需取消任务和在恢复应用程序时优雅地重新启动/通知用户,或者要求有限的时间来完成任务(例如完成下载)。

相关问题