Serializing UITextView with custom NSTextContainer does not restore text container

I have a UITextView using a custom subclassed NSTextContainer. My subclass is called

TDTBezierPathTextContainer
. I am creating the
UITextView
like this:


let textContainer = TDTBezierPathTextContainer(size:CGSize.zero) //NSTextContainer subclass
...
textView = UITextView(frame:r, textContainer:textContainer)


This all works, but I need to store and restore the exact state of the text view. For this, I am using the NSCoding protocol.


I am encoding the text view like this:


override public func encode(with aCoder: NSCoder) {
    super.encode(with: aCoder)
    aCoder.encode(textView, forKey: "textView")
}


I am decoding like this:

public required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    if let textView = aDecoder.decodeObject(forKey: "textView") as? UITextView {   
       textView.delegate = self
       addSubview(textView)
       self.textView = textView
    }
}


The problem is that encoding the

UITextView
does not encode my custom text container (even though it is in its graph and conforms to NSCoding). When I decode the text view, it seems to be using the default text container.


Apparently, the only way to specify the text container is when the

UITextView
is instantiated, so it seems impossible to restore my text view with my custom text container.


I have tried creating a new textview and setting all of the relevant properties the same, but the restore textview is slightly different.

Is there any way to store/restore a

UITextView
with a custom
NSTextContainer
intact?