Swift 使用Runtime对模型进行归档解档

Posted PLA-Artillery

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift 使用Runtime对模型进行归档解档相关的知识,希望对你有一定的参考价值。

Swift 使用Runtime对模型进行归档解档
func encode(with aCoder: NSCoder) {
        
        var count: UInt32 = 0
        let propertyList = class_copyPropertyList(self.classForCoder, &count)
        for index in 0..<Int(count) {
            guard let pty = propertyList?[index],
                let cName = property_getName(pty),
                let name = String(utf8String: cName) else {
                    continue
            }
            let value = self.value(forKey: name)
            aCoder.encode(value, forKey: name)
        }
        free(propertyList)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init()
        
        var count: UInt32 = 0
        let propertyList = class_copyPropertyList(self.classForCoder, &count)
        for index in 0..<Int(count) {
            guard let pty = propertyList?[index],
                let cName = property_getName(pty),
                let name = String(utf8String: cName) else {
                    continue
            }
            let value = aDecoder.decodeObject(forKey: name)
            self.setValue(value, forKey: name)
        }
        free(propertyList)
    }

在取值和赋值都是使用KVC:

取值:

let value = self.value(forKey: name)
aCoder.encode(value, forKey: name)

赋值:

let value = aDecoder.decodeObject(forKey: name)
self.setValue(value, forKey: name)

 

以上是关于Swift 使用Runtime对模型进行归档解档的主要内容,如果未能解决你的问题,请参考以下文章

iOS---归档与解档

ios 归档解档

iOS 归档解档

iOS解档与归档

面试iOS 开发面试题(三)

iOS 数据的归档(NSKeyedArchiver )与数据的解档(NSKeyedUnarchiver) 加密 提高安全性