我正在研究混合搭配 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/