似乎我的iOS应用程序中的多任务处理有问题。
我有一个正在运行的NSTimer,它会更新屏幕上的某些内容,而另一个NSTimer会在定义的时间间隔后仅触发一次。

问题是:我想对那个火灾事件使用react。我的应用程序是否在前台。

我使用以下代码来跟踪计时器:

-(void)backgroundThreadStarted {
  NSAutoreleasePool* thePool = [[NSAutoreleasePool alloc] init];

  // create a scheduled timer
  NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(backgroundThreadFire:) userInfo:nil repeats:YES];
  [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

  m_isBackgroundThreadToTerminate = NO;

  // create the runloop
  double resolution = 300.0;
  BOOL isRunning;
  do {
    // run the loop!
    NSDate* theNextDate = [NSDate dateWithTimeIntervalSinceNow:resolution];
    isRunning = [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:theNextDate];
    // occasionally re-create the autorelease pool whilst program is running
    [thePool release];
    thePool = [[NSAutoreleasePool alloc] init];
  } while(isRunning==YES && m_isBackgroundThreadToTerminate==NO);

  [thePool release];
}

-(void)backgroundThreadFire:(id)sender {
  // do repeated work every one second here

  // when thread is to terminate, call [self backgroundThreadTerminate];

}

-(void)backgroundThreadTerminate {
  m_isBackgroundThreadToTerminate = YES;
  CFRunLoopStop([[NSRunLoop currentRunLoop] getCFRunLoop]);
}

(在这里找到:http://www.cocoadev.com/index.pl?RunLoop)

我正在backgroundThreadStarted上调用-(void)applicationDidEnterBackground:(UIApplication *)application,在backgroundThreadTerminate上调用- (void)applicationWillEnterForeground:(UIApplication *)application,并且能够跟踪计时器。所以这很好用。

不幸的是,返回到应用程序后,整个屏幕都是黑色的。我尝试了不同的解决方案,但我在Google上搜索了很多,但都没有成功。

如果我在看到此黑屏的同时最小化该应用程序,则可以在将其设置为背景动画时看到该应用程序。

我想念什么?

如果我不做backgroundThread的东西,屏幕将显示正常。但后来,我无法跟踪计时器。

提前致谢!

最佳答案

您正在使用AppKit(OS X)而非UIKit(iOS)的代码。

您应该查看将涉及处理didEnterBackground的后台API,并在其中使用beginBackgroundTaskWithExpirationHandler创建后台任务:

不需要后台线程(它们用于在应用程序仍在运行时在应用程序的后台运行的事物)。后台任务是一种在应用程序不再位于前台时让常规应用程序代码运行(无UI交互)的方法。您将无法在本地通知服务之外与用户轻松地就此进行交流(API的目的更多是为了让您在离开应用程序后完成上传)。并且您的任务仅限于后台运行后的十分钟。

10-08 20:06