Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

swift - How to use Codable protocol in objective c data model class?

I am working on mix and match iOS source code. I have implemented codable for swift data model class which reduces the burden of writing parser logic. I tried to conform my objective c class to codable protcol which in turn thrown an error "Cannot find protocol declaration for 'Codable'". Is there any way to use this swift protocol into objective c class? Or Is there any other objective c api that provides the same capability as Codable? The idea is to make the parsing logic same across swift and objective c classes.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, you can use Codable together with Obj-C. The tricky part is that because Obj-C can't see Decoder, so you will need to create a helper class method when you need it to be allocated from Obj-C side.

public class MyCodableItem: NSObject, Codable {
    private let id: String
    private let label: String?

    enum CodingKeys: String, CodingKey {
        case id
        case label
    }

    @objc public class func create(from url: URL) -> MyCodableItem {
        let decoder = JSONDecoder()
        let item = try! decoder.decode(MyCodableItem.self, from: try! Data(contentsOf: url))
        return item
    }

    public required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decode(String.self, forKey: .id)
        label = try? container.decode(String.self, forKey: .label)
        super.init()
    }

    required init(coder decoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...