如何为包含非Codable类型的ReSwift状态实现自定义序列化逻辑
首先可以通过JSONEncoder/JSONDecoder实现需求,不需要在状态中存储中间Codable结构体
你只需要为你的窗口状态类型编写自定义的encode(to:)和init(from:)方法,在序列化时动态将非Codable的原生对象转换为可编码的中间数据,反序列化时再直接还原为原生对象即可,平时状态中直接存储原生类型使用,仅在序列化/反序列化环节做转换,完全规避了你提到的频繁转换的繁琐和性能损耗。
以PDFSelection为例,参考实现如下:
import PDFKit import Foundation struct WindowState: Codable { // 状态中直接存储原生非Codable类型 let pdfURL: URL var currentPageIndex: Int var currentSelection: PDFSelection? enum CodingKeys: String, CodingKey { case pdfURL, currentPageIndex, selectionMeta } // 自定义编码逻辑 func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(pdfURL, forKey: .pdfURL) try container.encode(currentPageIndex, forKey: .currentPageIndex) // 编码时临时将PDFSelection转为可序列化的页码+范围结构 guard let selection = currentSelection else { return } var selectionMeta: [Int: NSRange] = [:] for pageIdx in 0..<selection.numberOfPages { let page = selection.page(at: pageIdx) guard let docPageIdx = page.document?.index(for: page) else { continue } selectionMeta[docPageIdx] = selection.range(for: page) } try container.encode(selectionMeta, forKey: .selectionMeta) } // 自定义解码逻辑 init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.pdfURL = try container.decode(URL.self, forKey: .pdfURL) self.currentPageIndex = try container.decode(Int.self, forKey: .currentPageIndex) // 解码时直接还原为PDFSelection原生对象 guard let pdfDoc = PDFDocument(url: pdfURL) else { throw DecodingError.dataCorruptedError(forKey: .pdfURL, in: container, debugDescription: "PDF文档加载失败") } guard let selectionMeta = try container.decodeIfPresent([Int: NSRange].self, forKey: .selectionMeta) else { self.currentSelection = nil return } let selection = PDFSelection(document: pdfDoc) for (pageIdx, range) in selectionMeta { guard let page = pdfDoc.page(at: pageIdx), let pageSelection = PDFSelection(document: pdfDoc) else { continue } pageSelection.add([page], for: range) selection.add(pageSelection) } self.currentSelection = selection } // 普通初始化方法,业务层直接调用,不需要感知编解码逻辑 init(pdfURL: URL, currentPageIndex: Int, currentSelection: PDFSelection?) { self.pdfURL = pdfURL self.currentPageIndex = currentPageIndex self.currentSelection = currentSelection } }
如果不想自行维护转换逻辑,可选择以下替代方案
方案1:使用NSKeyedArchiver做序列化
PDFKit的大部分原生类型都默认遵守NSSecureCoding协议,你可以直接将整个状态类继承自NSObject并实现NSSecureCoding,用系统提供的序列化能力直接处理原生对象,不需要写任何自定义转换逻辑,性能也比JSON方案更高。
参考实现:
class WindowState: NSObject, NSSecureCoding { static var supportsSecureCoding: Bool = true let pdfURL: URL var currentPageIndex: Int var currentSelection: PDFSelection? func encode(with coder: NSCoder) { coder.encode(pdfURL, forKey: "pdfURL") coder.encode(currentPageIndex, forKey: "currentPageIndex") coder.encode(currentSelection, forKey: "currentSelection") } required init?(coder: NSCoder) { guard let pdfURL = coder.decodeObject(of: NSURL.self, forKey: "pdfURL") as? URL else { return nil } self.pdfURL = pdfURL self.currentPageIndex = coder.decodeInteger(forKey: "currentPageIndex") self.currentSelection = coder.decodeObject(of: PDFSelection.self, forKey: "currentSelection") } init(pdfURL: URL, currentPageIndex: Int, currentSelection: PDFSelection?) { self.pdfURL = pdfURL self.currentPageIndex = currentPageIndex self.currentSelection = currentSelection } } // 调用示例 // 序列化 let stateData = try NSKeyedArchiver.archivedData(withRootObject: windowState, requiringSecureCoding: true) // 反序列化 guard let restoredState = try NSKeyedUnarchiver.unarchivedObject(ofClass: WindowState.self, from: stateData) else { // 处理还原失败逻辑 }
方案2:全局扩展非Codable类型的Codable能力
如果项目中多处需要序列化同一个非Codable类型,你可以单独为该类型添加Codable扩展,全局实现其编解码逻辑,后续所有用到该类型的地方都可以直接使用默认的JSON编解码能力,无需重复写转换代码。
内容的提问来源于stack exchange,提问作者Thom Smith
相关产品推荐
相关产品推荐

