objective-c - 如何在 Objective C 数据模型类中使用 Codable 协议(protocol)?

标签 objective-c swift codable

我正在研究混合搭配 iOS 源代码。我已经为 swift 数据模型类实现了可编码,这减少了编写解析器逻辑的负担。我试图使我的 objective-c 类符合可编码协议(protocol),这又引发了错误“找不到‘可编码’的协议(protocol)声明”。有什么办法可以在 Objective C 类中使用这个 swift 协议(protocol)吗?或者是否有其他 objective-c api 提供与 Codable 相同的功能?这个想法是让 swift 和 Objective C 类的解析逻辑相同。

最佳答案

是的,您可以将 Codable 与 Obj-C 一起使用。棘手的部分是,因为 Obj-C 无法看到 Decoder,所以当您需要从 Obj-C 端分配它时,您需要创建一个辅助类方法。

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")
    }
}

关于objective-c - 如何在 Objective C 数据模型类中使用 Codable 协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54643080/

相关文章:

ios - 如何通过点击更改 map 注释位置并且仍然能够平移? (包括gif)

ios - 更改数组中的值

swift - 使用可选类型时的 RealmSwift 和 Codable

json - swift 4.2 : Type 'T' does not conform to protocol 'Decodable'

ios - 什么是操作系统状态?

iOS 自定义 UItableviewcell 部分

Objective-C:如何将对象作为 block 参数传递给需要其基类的方法?

objective-c - 自定义控件中的多个凹进 NSButtonCell

ios - 核心数据 swift : Fatal error: unexpectedly found nil while unwrapping an Optional value

swift - 使用 Swift JSONEncoder 编码时会发生什么错误