码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-04-05 19:18:56      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:ade   runtime   let   swift   false   归档   strong   guard   font   

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对模型进行归档解档

标签:ade   runtime   let   swift   false   归档   strong   guard   font   

原文地址:http://www.cnblogs.com/PLA-Artillery/p/6669994.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!