最新消息:20190717 VPS服务器:Vultr新加坡,WordPress主题:大前端D8,统一介绍入口:关于

【已解决】iOS中如何恢复和保存一个Singleton类型的视图控制器

iOS crifan 695浏览 0评论

之前实现一个自定义的视图控制器,然后被代码调用:

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

转载请注明:在路上 » 【已解决】iOS中如何恢复和保存一个Singleton类型的视图控制器

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
60 queries in 0.119 seconds, using 19.01MB memory