Swift存储和恢复button上的ViewController状态点击

我正在使用Xcode 8和Swift 2.3

我浏览了几个网站,这些网站是关于国家恢复方法的指南:

State Restoration Tutorial: Getting Started

https://github.com/shagedorn/StateRestorationDemo/blob/master/StateRestorationDemo/CityViewController.swift

但我需要存储和恢复视图控制器的状态button点击通过确定的关键。

我不能使用故事板中的单一标识符,因为我需要保存同一个viewcontroller的许多实例,所以需要为每个实例使用不同的标识符,基于传递的密钥标识符,它应该只恢复相同视图控制器的特定实例

func sevNameVccBtnFnc(identifierKey :String) { // How to manually call encodeRestorableStateWithCoder } func revNameVccBtnFnc(identifierKey :String)->nameVcc { // How to manually call decodeRestorableStateWithCoder } 

AppDelegate代码:

 func application(application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool { return true } func application(application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool { return true } 

ViewController代码:

 class nameVcc: UIViewController, UIViewControllerRestoration { override func viewDidLoad() { super.viewDidLoad() } override func encodeRestorableStateWithCoder(coder: NSCoder) { print("encodeRestorableStateWithCoder") super.encodeRestorableStateWithCoder(coder) } override func decodeRestorableStateWithCoder(coder: NSCoder) { print("decodeRestorableStateWithCoder") super.decodeRestorableStateWithCoder(coder) } static func viewControllerWithRestorationIdentifierPath(identifierComponents: [AnyObject], coder: NSCoder) -> UIViewController? { print("viewControllerWithRestorationIdentifierPath") let vc = nameVcc() return vc } } 

但我需要存储和恢复视图控制器的状态button点击通过确定的关键。

不。 这不能通过点击button来完成。 UIKit仅在应用程序进入BG模式时才提供编码器来编码您的数据。 有很可能没有办法手动调用这些方法。 状态保存/恢复不是为此devise的,或者至lessUIKit现在不允许这样做。 您可能必须自己编写自己的状态恢复机制,例如UserDefaults或写入磁盘。