我试图让我的游戏保持当前状态,并在用户退出或重新启动游戏时重新加载。然而,我正在努力的是如何在正确的时间实际访问对象。这是我需要的伪代码,我似乎无法访问正确的对象,我是向后做这个还是这是正确的方法呢?
重申一下,我的问题是访问正确的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
}
奖金问题:这两个功能是正确的保存/加载吗?
答案 0 :(得分:1)
或者,您可以在代码中的任何位置设置通知处理程序:
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(handleEnteredBackground:)
name: UIApplicationDidEnterBackgroundNotification
object: nil];
答案 1 :(得分:1)
解决这个问题的正确方法是使用模型 - 视图 - 控制器模式(MVC) - 因为(几乎)所有优秀的Cocoa iOS应用程序应该:
UIApplicationWillEnterBackgroundNotification
作为将状态保存到模型的触发器。applicationDidEnterBackground:
消息时,将模型对象中的数据保存到文件系统。应用程序代理不应该从每个视图控制器中挑选出要保存到文件系统的信息。