Adding NSCoding as an Extension
Asked Answered
S

1

16

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 ?

Silurid answered 2/9, 2014 at 20:21 Comment(0)
M
13

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.

Movable answered 9/11, 2014 at 4:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.