美文网首页
ios runtime 自动解归档

ios runtime 自动解归档

作者: biubiubiuCOWARD | 来源:发表于2019-03-26 14:04 被阅读0次

在正常项目中,需要将模型model本地化存储就必须用到解归档,解归档需要将模型中的所有的属性都一一写一遍非常麻烦,可以通过runtime快速完成自动解归档操作。

    // 归档
    func encode(with aCoder: NSCoder) {
        var c = self.classForCoder
        while c != NSObject.self {
            var count: UInt32 = 0
            // 获得class中所有属性
            guard let ivars = class_copyIvarList(c, &count) else { return }
            for i in 0..<count {
                let key = NSString(utf8String: ivar_getName(ivars[Int(i)])!)! as String
                let value = self.value(forKey: key)
                aCoder.encode(value, forKey: key)
            }
            // 获得父类
            c = c.superclass()!
            // 释放
            free(ivars)
        }
    }
    // 解归档
    required init?(coder aDecoder: NSCoder) {
        super.init()
        var c = self.classForCoder
        while c != NSObject.self {
            var count: UInt32 = 0
            // 获得class中所有属性
            guard let ivars = class_copyIvarList(c, &count) else { return }
            for i in 0..<count {
                let key = NSString(utf8String: ivar_getName(ivars[Int(i)])!)! as String
                let value = aDecoder.decodeObject(forKey: key)
                self.setValue(value, forKey: key)
            }
            // 获得父类
            c = c.superclass()!
            // 释放
            free(ivars)
        }
    }

相关文章

  • ios runtime 自动解归档

    在正常项目中,需要将模型model本地化存储就必须用到解归档,解归档需要将模型中的所有的属性都一一写一遍非常麻烦,...

  • runtime自动归档

    前言 善用runtime,可以解决自动归档解档。想想以前归档是手动写的,确实太麻烦了。现在有了runtime,我们...

  • runtime自动归档/解档

    前言 善用runtime,可以解决自动归档解档。想想以前归档是手动写的,确实太麻烦了。现在有了runtime,我们...

  • runTime

    iOS runtime讲解,并且用runtime动态归档与解档 (2015-09-30 22:42:02)转载▼ ...

  • runtime使用 自定义数据类型的编码解码

    通过runtime 遍历自定义model的所有属性实现归档解档操作。 要实现我们自定义的model能够自动解档归档...

  • runtime自动解档归档

    如果你实现过自定义模型数据持久化的过程,那么你也肯定明白,如果一个模型有许多个属性,那么我们需要对每个属性都实现一...

  • iOS - runtime-04实现自动解归档

    通过 runtime 进行归档、解档很节省很多工作,我先贴一段常规的解归档的代码。 通过这种方式进行解归档很麻烦,...

  • iOS Runtime归档解档

    利用运行时实现归档、解档,并将其封装成宏 继承 NSObject 并遵守 NSCoding 协议,创建一个类 在 ...

  • iOS runtime 归档解档

    创建Person类 .h文件 #import #import ...

  • ios中Swift的归档与解档

    ios中Swift的归档与解档 归档 解档 init()方法 设置属性

网友评论

      本文标题:ios runtime 自动解归档

      本文链接:https://www.haomeiwen.com/subject/geugvqtx.html