如何在目标c数据模型类中使用Codable协议? [英] How to use Codable protocol in objective c data model class?
问题描述
我正在研究混合匹配的iOS源代码.我为快速数据模型类实现了可编码,从而减少了编写解析器逻辑的负担.我试图使我的目标c类符合可编码协议,从而引发错误找不到可编码的协议声明".有什么方法可以将此快速协议用于目标c类吗?还是有其他目标c api提供与Codable相同的功能?这样做的目的是使快速和客观c类之间的解析逻辑相同.
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.
推荐答案
是的,您可以将Codable与Obj-C一起使用.棘手的是,因为Obj-C看不到Decoder
,所以当需要从Obj-C端分配它时,您将需要创建一个辅助类方法.
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")
}
}
这篇关于如何在目标c数据模型类中使用Codable协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!