Adding NSCoding as an Extension

房东的猫 提交于 2019-12-03 16:54:20

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/25631727/adding-nscoding-as-an-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!