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

标签 objective-c swift codable

我正在混合搭配 iOS 源代码。我已经为 swift 数据模型类实现了可编码,这减少了编写解析器逻辑的负担。我试图使我的 objective-c 类符合可编码协议(protocol),这又引发了错误“找不到‘可编码’的协议(protocol)声明”。有没有办法将这个快速协议(protocol)用于 objective-c 类?或者是否有任何其他 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/50617542/

相关文章:

swift - 在 ZStack 中对齐对象

ios - 添加到 MKMapView 时出现 UILongPressGestureRecognizer 问题

swift - 在 Swift 中使用 Codable 解析 JSON 数据

json - 使用 Codable swift 解析时忽略数组中的空对象

objective-c - 发布应用程序中的 Obj-C NDEBUG 问题

ios - 卸载 iOS 应用程序后显示消息

iOS 画中画如果延迟加载则无法启动

objective-c - 是否可以防止 Objective-C 中的 POSIX 符号名称污染?

ios - 如何在早上 8 点发出每日通知? ( swift 3)

swift - 在 Swift 4 中解码可选字典而不进行实际映射