iOS开发之Swift一键Encode&Decode + 字典初始化模型

Git连接:https://github.com/BBHNation/EncodeModel
/*
* 新加入了Dic转Model的功能,当然是使用了Runtime来获取dic信息匹配到Model中
*/

作用:

继承BaseEncodeModel,可以方便的归档解档,不用一行一行写归档代码和解档属性配置。
继承BaseEntity,可以在归档解档前提下实现字典初始化。
Git中是一个EncodeModel,作为基类,可以方便iOS中的Encode和Decode过程。

源代码:

import Foundation

class BaseEncodeModel : NSObject, NSCoding {
    override init() {}
    
    /// 获取所有的属性名字
    ///
    /// - Returns: 返回一个数组,带有属性名字
    func getPropertyNameList() -> [String] {
        var count : UInt32 = 0
        var names : [String] = []
        let properties = class_copyPropertyList(type(of: self), &count)
        guard let propertyList = properties else { return [] }
        for i in 0..<count {
            let property = propertyList[Int(i)]
            guard let char_b = property_getName(property) else {
                continue //到下一个循环
            }
            if let key = NSString(cString: char_b, encoding: String.Encoding.utf8.rawValue) as String? {
                names.append(key)
            }
        }
        return names
    }

/// 协议方法
///
/// - Parameter aCoder: 编码
func encode(with aCoder: NSCoder) {
    let propertyList = getPropertyNameList()
    for p_name in propertyList {
        aCoder.encode(value(forKey: p_name), forKey: p_name)
    }
    print("encode successful")
}

/// 协议方法
///
/// - Parameter aDecoder: 解码
required init?(coder aDecoder: NSCoder) {
    super.init()
    let propertyList = getPropertyNameList()
    for p_name in propertyList {
        let value = aDecoder.decodeObject(forKey: p_name)
        setValue(value, forKey: p_name)
    }
}

    /// 实例方法,开始编码
    ///
    /// - Parameter fileName: 文件名字
    func archive(fileName: String) {
        let filePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!
        let savePath = filePath + "/" + fileName + ".plist"
        NSKeyedArchiver.archiveRootObject(self, toFile: savePath)
    }
    
    /// 类方法,开始解码
    ///
    /// - Parameter fileName: 文件名字
    /// - Return: 返回一个实例,可以为空
    static func unarchive(fileName: String) -> Any? {
        let filePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!
        let savePath = filePath + "/" + fileName + ".plist"
        return NSKeyedUnarchiver.unarchiveObject(withFile: savePath)
    }
}

使用方法:

  • 第一步 需要类继承于BaseEncodeModel
class Demo: BaseEncodeModel {
    var name : String = ""
    var age : Int = 0
    var gender : Bool = false
    var content : String = ""
}
  • 第二步 设置实例属性,并使用实例方法来Encode
let demo = Demo.init()
demo.content = content.text!
demo.age = 22
demo.name = "BBH"
demo.gender = true
demo.archive(fileName: "helloFileName")
  • 第三步 使用类方法来Decode
 let demo = Demo.unarchive(fileName: "helloFileName") as? Demo
print("name:\(demo?.name ?? ""), age:\(demo?.age ?? 0), gender:\(demo?.gender ?? false)")

推荐阅读更多精彩内容