-
备忘录(Memento)模式备忘录模式快照对象的内部状态并将其保存到外部。换句话说,它将状态保存到某处,过会你可以不破坏封装的情况下恢复对象的状态,也就是说原来对象中的私有数据仍然是私有的。如何使用备忘录模式在ViewController.m中增加下面的方法:Objective-c代码- (void)saveCurrentState{// When the user leaves the app and then comes back again, he wants it to be in the exact same state// he left it. In order to do this we need to save the currently displayed album.// Since it's only one piece of information we can use NSUserDefaults.[[NSUserDefaultsstandardUserDefaults] setInteger:currentAlbumIndex forKey:@"currentAlbumIndex"];}- (void)loadPreviousState{currentAlbumIndex = [[NSUserDefaultsstandardUserDefaults] integerForKey:@"currentAlbumIndex"];[self showDataForAlbumAtIndex:currentAlbumIndex];}saveCurrentState 保存当前的专辑索引到NSUserDefaults,NSUserDefaults是 IOS提供的保存应用设置信息和数据的地方。loadPreviousState 加载之前保存的索引。这里其实不是备忘录模式完整的实现,但是你已经了解到它了。现在,在ViewController.m的viewDidLoad方法中,在scroller初始化之前增加下面的代码:Objective-c代码[self loadPreviousState];它将在应用启动的时候加载原先保存的状态。但是在什么时候来保存应用的状态呢?你将使用通知来实现它。当应用进入后台的时候,IOS会发送UIApplicationDidEnterBackgroundNotification通知,你可以使用这个通知去保存状态,这是不是很方便?在viewDidLoad中增加下面的代码:Objective-c代码[[NSNotificationCenterdefaultCenter] addObserver:self selector:@selector(saveCurrentState) name:UIApplicationDidEnterBackgroundNotification object:nil];现在,当应用进入后台的时候,ViewController将通过saveCurrentState方法自动保存当前的状态。现在增加下面的代码:Objective-c代码- (void)dealloc{[[NSNotificationCenterdefaultCenter] removeObserver:self];}这将确保当ViewController被销毁的时候移除观察者。构建和运行你的应用,导航到一个专辑,然后通过Command+Shift+H(模拟器的情况下)将app发送到后台,然后关闭app。再一次打开app,检查原先选择的专辑是不是被显示在中间:看起来专辑数据是正确的,但是中间的视图却没有显示正确的专辑。出了什么情况?这是可选方法initialViewIndexForHorizontalScroller的目的所在。因为这个方法没有在委托中实现,这样的话初始化视图总是第一个视图。为了修正这个问题,在ViewController.m中增加下面的代码:Objective-c代码- (NSInteger)initialViewIndexForHorizontalScroller:(HorizontalScroller *)scroller{return currentAlbumIndex;}现在HorizontalScroller的第一个视图终于设置为了currentAlbumIndex指定的视图。这使得app在下次使用的时候还保留了上次使用的状态。
IOS设计模式之(备忘录模式,命令模式)
最新推荐文章于 2025-02-11 17:30:00 发布