应用程序进入/离开后台时保存和加载数据

时间:2013-12-05 13:00:20

标签: ios iphone objective-c appdelegate nskeyedarchiver

我试图让我的游戏保持当前状态,并在用户退出或重新启动游戏时重新加载。然而,我正在努力的是如何在正确的时间实际访问对象。这是我需要的伪代码,我似乎无法访问正确的对象,我是向后做这个还是这是正确的方法呢?

重申一下,我的问题是访问正确的ViewControllers以便从磁盘保存/加载数据。

我的导航层次结构很简单,ViewController > GameViewController(以模态显示)

-(void)applicationDidEnterBackground:(UIApplication *)application
{
  // Save current state to disk

  // See if GameViewController (or GameView) is top controller (aka game in progress)
  // If so then use NSKeyedArchiver to persist to disk
}

-(void)applicationDidBecomeActive:(UIApplication *)application
{
  // Load current state from disk

  // Use NSKeyedArchiver to load data from disk, if game is in progress then
  // Find mainViewController, then show the game modal on top of it
  // then populate the game data with the data from disk
}

奖金问题:这两个功能是正确的保存/加载吗?

2 个答案:

答案 0 :(得分:1)

或者,您可以在代码中的任何位置设置通知处理程序:

[[NSNotificationCenter defaultCenter] addObserver: self
                                         selector: @selector(handleEnteredBackground:) 
                                             name: UIApplicationDidEnterBackgroundNotification
                                           object: nil];

答案 1 :(得分:1)

解决这个问题的正确方法是使用模型 - 视图 - 控制器模式(MVC) - 因为(几乎)所有优秀的Cocoa iOS应用程序应该:

  • 首先,确保您要保留的所有数据都存储在模型图层/对象中。
  • 如果视图控制器的状态经常更改,请使用视图控制器中的通知:UIApplicationWillEnterBackgroundNotification作为将状态保存到模型的触发器。
  • 当在app delegate中收到applicationDidEnterBackground:消息时,将模型对象中的数据保存到文件系统。
  • 当应用程序唤醒或重新启动时,将文件数据加载回模型并通过自定义通知通知视图控制器,以便视图控制器知道恢复其相关状态。

应用程序代理不应该从每个视图控制器中挑选出要保存到文件系统的信息。