You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift:用Codable实现NSCoding,从Data创建Decoder的方法

用Codable复用逻辑消除NSCoding样板代码的方案

这个场景我之前也碰到过,要兼顾遗留的NSCoding要求又想利用Codable省掉重复代码,其实只要把Codable的编解码和NSCoding的逻辑打通就行,核心就是用JSONDecoder或者PropertyListDecoder从拿到的Data生成Decoder实例,直接复用Codable的初始化方法。

下面给你补全完整的可运行代码示例:

class Something: NSCoding, Codable {
    // 示例属性,根据你的实际需求替换
    let itemName: String
    let itemCount: Int
    
    // 常规初始化方法
    init(itemName: String, itemCount: Int) {
        self.itemName = itemName
        self.itemCount = itemCount
    }
    
    // MARK: - NSCoding 协议实现
    public convenience required init?(coder aDecoder: NSCoder) {
        // 先从NSCoder里取出之前存的Data
        guard let data = aDecoder.decodeObject(forKey: "encodedData") as? Data else {
            print("无法从NSCoder获取Data")
            return nil
        }
        
        // 选择对应的Decoder:如果用PropertyList存储就换成PropertyListDecoder
        let decoder = JSONDecoder()
        do {
            // 调用Codable自动生成的init(from:)方法
            try self.init(from: decoder.decode(Self.self, from: data))
        } catch {
            print("Codable解码失败:\(error.localizedDescription)")
            return nil
        }
    }
    
    public func encode(with aCoder: NSCoder) {
        // 选择和Decoder对应的Encoder,保持类型一致
        let encoder = JSONEncoder()
        do {
            // 用Codable自动生成的encode(to:)方法生成Data
            let data = try encoder.encode(self)
            aCoder.encode(data, forKey: "encodedData")
        } catch {
            print("Codable编码失败:\(error.localizedDescription)")
        }
    }
    
    // MARK: - Codable 自动生成逻辑
    // 只要你的属性都支持Codable(系统基础类型、自定义类型也实现Codable),这里不需要手动写CodingKeys、init(from:)和encode(to:)
    // 系统会自动帮你生成,彻底省掉NSCoding的样板代码!
}

几个关键注意点:

  • 编解码类型要匹配:如果用JSONEncoder生成Data,就必须用JSONDecoder解码;如果是用属性列表(PropertyList)存储,就对应PropertyListEncoder和PropertyListDecoder,不然会解码失败。
  • 错误处理要严谨:别用try?直接忽略错误,用do-catch捕获并打印错误信息,方便调试排查问题。
  • 自定义类型兼容:如果你的类里包含自定义子对象,只要子对象也实现了Codable,整个编解码逻辑就能自动工作,不需要再为子对象写NSCoding的样板代码。

内容的提问来源于stack exchange,提问作者aryaxt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:43:28