2

I have a class that implements NSCoding and holds a reference to a UIView object...

class A: NSObject, NSCoding {
    var view: UIView!

    init(view: UIView) {
        super.init()
        commonInit(view)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit(/* <Need to pass the existing view somehow> */)
    }

    override func encodeWithCoder(aCoder: NSCoder) {
        super.encodeWithCoder(aCoder)
    }
}

The view passed is a particular heavyweight custom view class that I don't need to serialise. There are many A objects and they all reference this same custom UIView. But during state restoration I need a reference to it in order to restore instances of A. The view instance already exists at the point I need it, and my custom UIViewController actually initiates the decoding sequence:

override func decodeRestorableStateWithCoder(coder: NSCoder) {
   // How to get self.customView to A.init?(coder aDecoder: NSCoder) where 
   // it is needed?
   let view = self.customView   
   self.a = coder.decodeObjectForKey("aKey") as! A
}

But how can I make the existing view available to A.init?(coder aDecoder: NSCoder)?

sleep
  • 4,855
  • 5
  • 34
  • 51
  • 1
    Short answer is you can't. You'll have to provide some sort of fix-up post serialization. – trojanfoe May 31 '16 at 07:06
  • Dang, thought that might be the case, some kind of two-step init. All that would be needed would be for NSCoder to allow something like `setObjectReference(obj: AnyObject, forKey: String)` – sleep May 31 '16 at 07:12

0 Answers0