ios - 在 ApplicationWillResignActive 中查看 Controller 变量

标签 ios objective-c background nstimer

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

NSTimeInterval idleTime = [dateReturnedToForeground timeIntervalSinceDate:dateEnteredBackground];
NSTimeInterval elapsedTime = [[NSDate date] timeIntervalSinceDate:startDate];
elapsedTime -= idleTime;

每个 View Controller (和计时器/时间间隔)的访问方式如下:
-(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];
}

我将每个 View Controller 添加到通知中心,以便可以在应用程序委托(delegate)中访问它(我认为这是对的?)。问题是,我不知道如何将第一个代码与 View Controller 代码结合起来,因为我无法在应用程序委托(delegate)中访问 View Controller 的属性。有什么建议可以让我的计时器在后台“运行”吗?

最佳答案

你对这一切都错了。无需在应用程序委托(delegate)中执行任何此操作。

让每个 View Controller 监听 UIApplicationWillResignActiveNotification通知。然后每个 View Controller 可以在收到通知时做任何它认为合适的事情来保存它的数据。

更新:

在 View Controller 的 init...方法,注册通知:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resigningActive) name:UIApplicationWillResignActiveNotification object:nil];

在 View Controller 的 dealloc方法,注销:
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
}

然后执行 resigningActive方法:
- (void)resigningActive {
    // The app is resigning active - do whatever this view controller needs to do
}

关于ios - 在 ApplicationWillResignActive 中查看 Controller 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18222052/

相关文章:

objective-c - 桌面文件和背景之间的窗口

extjs 根据值更改网格单元格背景

javascript - 使用 javascript 调整 Image() 对象大小不起作用

ios - AudioKit 后台音频电池使用

ios - Facebook SDK 3.1 : Feed Dialog vs Native dialog

iphone - iOS:if-else 在 stringwithformat 中

objective-c - iOS 和 ARC : How to retain self during asynchronous operations?

ios - 如何让一个自由下落的 Sprite 节点坐在另一个水平移动的 Sprite 身上

ios - UITableViewCell 中 UITextView 的奇怪行为

ios - 更改 UILabel 文本