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)

 

posted @ 2017-04-05 18:20  乐启榜  阅读(613)  评论(0编辑  收藏  举报