在ApplicationWillResignActive中查看控制器变量

Evi*_*gis 1 background objective-c nstimer ios

我正在尝试通过在进入后台时将时间保存到磁盘并在进入前台时检索它来让我的计时器在后台"运行".每个视图控制器都有一个计时器和用户指定的timeInterval.问题是,我不知道如何访问timeInterval变量.我想我可以通过使用这样的东西来获得时间的差异(这会起作用吗?):

NSTimeInterval idleTime = [dateReturnedToForeground timeIntervalSinceDate:dateEnteredBackground];
NSTimeInterval elapsedTime = [[NSDate date] timeIntervalSinceDate:startDate];
elapsedTime -= idleTime;
Run Code Online (Sandbox Code Playgroud)

每个视图控制器(和计时器/时间间隔)的访问方式如下:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DetailViewController *detailVC;
    if (![self.detailViewsDictionary.allKeys containsObject:indexPath]){
        detailVC = [[DetailViewController alloc]initWithNibName:@"DetailViewController" bundle:nil];
        [self.detailViewsDictionary setObject:detailVC forKey:indexPath];
        detailVC.context = self.managedObjectContext;
    }else{
        detailVC = self.detailViewsDictionary[indexPath];
    }
        Tasks *task = [[self fetchedResultsController] objectAtIndexPath:indexPath];
        detailVC.testTask = task;
        [[self navigationController] pushViewController:detailVC animated:YES];
    NSLog(@"%@", self.detailViewsDictionary);
    [[NSNotificationCenter defaultCenter] addObserver:detailVC forKeyPath:self.detailViewsDictionary[indexPath] options:nil context:nil];
}
Run Code Online (Sandbox Code Playgroud)

我将每个视图控制器添加到通知中心,以便可以在应用程序委托中访问它(我认为这是正确的?).问题是,我不知道如何将第一个代码与视图控制器代码结合起来,因为我无法在app delegate中访问视图控制器的属性.任何建议,以便我可以让我的计时器在后台"运行"?

rma*_*ddy 8

你这一切都错了.在app委托中不需要执行任何操作.

让每个视图控制器监听UIApplicationWillResignActiveNotification通知.然后,每个视图控制器都可以在收到通知时执行任何适合保存其数据的感觉.

更新:

在视图控制器的init...方法中,注册通知:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resigningActive) name:UIApplicationWillResignActiveNotification object:nil];
Run Code Online (Sandbox Code Playgroud)

在视图控制器的dealloc方法中,取消注册:

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
}
Run Code Online (Sandbox Code Playgroud)

然后实现resigningActive方法:

- (void)resigningActive {
    // The app is resigning active - do whatever this view controller needs to do
}
Run Code Online (Sandbox Code Playgroud)