之前实现一个自定义的视图控制器,然后被代码调用:
self.showViewController(gMainNVC, sender: gMainNVC) |
后,保存和恢复的函数,会被调用到:
encodeRestorableStateWithCoder
decodeRestorableStateWithCoder
但是现在由于变成了单实例:
class SingletonMainVC { static let sharedInstance = MainViewController() private init() {} } class SingletonMainNVC { static let sharedInstance = UINavigationController(rootViewController:SingletonMainVC.sharedInstance) private init() { // SingletonMainNVC.sharedInstance.restorationIdentifier = "SingletonMainNVC" SingletonMainNVC.sharedInstance.restorationIdentifier = String(self.dynamicType) print("SingletonMainNVC.sharedInstance.restorationIdentifier=\(SingletonMainNVC.sharedInstance.restorationIdentifier)") } } //func resetMainVC() -> MainViewController { // gMainVC = MainViewController() // gMainNVC = UINavigationController(rootViewController:gMainVC) // gMainNVC.restorationIdentifier = "gMainNavigationController" // // return gMainVC //} |
导致之前的恢复和保存都调用不到了
搜:
ios singleton restore
ios – Multiple storyboards: should I use a singleton pattern to cache them? – Stack Overflow
ios – Can’t restore archived data – Stack Overflow
iOS: How can I destroy a Singleton in ARC? Should I? – Stack Overflow
去看看restorationIdentifier,是UIViewController针对于UIStateRestoring的扩展:
extension UIViewController : UIStateRestoring { @available(iOS 6.0, *) public var restorationIdentifier: String? @available(iOS 6.0, *) public var restorationClass: AnyObject.Type? @available(iOS 6.0, *) public func encodeRestorableStateWithCoder(coder: NSCoder) @available(iOS 6.0, *) public func decodeRestorableStateWithCoder(coder: NSCoder) @available(iOS 7.0, *) public func applicationFinishedRestoringState() } |
所以:
想办法把SingletonMainVC改为:
class SingletonMainVC:MainViewController { static let sharedInstance = MainViewController() private override init() { super.init() self.restorationIdentifier = String(self.dynamicType) self.restorationClass = self.dynamicType } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } |
-》但是好像又无法起到单实例的目的了。。。。
iBombSite: [iOS] Saving the Singleton Object’s State to File