I'd like to extend a framework class (I don't want to edit the source code directly), and make it conform to NSCoding
.
Basically, here's a simplification of the situation I'm in :
/* Can't be edited. */
class Car: NSObject {
var color: String?
}
/* Can be edited */
extension Car: NSCoding {
init(coder aDecoder: NSCoder) {
}
func encodeWithCoder(aCoder: NSCoder) {
}
}
The issue is init(coder aDecoder: NSCoder)
is, as per the header file, a designated initializer
(isn't this weird though ? shouldn't it be a convenience initializer
?). However, the documentation says extension can't add a new designated initializer.
My English isn't perfect and maybe I missed something out... Or is it really impossible ?
Like the documentation says, extensions can't add new designated initializers. What if there were private properties that need initialization? It would be impossible to properly initialize the type. You can add convenience initializers in an extension because by their nature, they must call a designated initializer.
Also, init(coder aDecoder: NSCoder) is specified to be a designated initializer because it is a whole different route to creating an instance. Take UIViewController for instance, it can be created using plain code or it can be created from a XIB file.
In the end, it is not possible to add an extension that implements NSCoding.
Perhaps you can create a wrapper class that contains this class and have it implement NSCoding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With