Swift-自动归档(改进)

前言:使用自动归档我们需要遵守NSCoding协议,但是通过一些JsonModel的工具来完成转Model后,比如遵守HandyJSON,再遵守NSCoding协议,会出现冲突Multiple inheritance from classes 'BaseModel' and 'NSCoder',这里暂时只用了HandyJSON来转Model,其他工具未知

import HandyJSON
// -MARK: 继承此model不用重写init()函数
class BaseModel: HandyJSON {
    required init() {}
}

工具使用
        var dic = [String: Any]()
        dic["id"] = Int(tf_1.text!) // 因为模型指定的是Int 类型的 必须转成指定类型不然会失败 
        dic["name"] = tf_2.text
        dic["age"] = Int(tf_3.text!)
        dic["phone"] = tf_4.text
        guard let json = dic.hw_toJSONString() else {
            print("出错")
            return
        }
        UserTool.saveUser(json) // 存
        guard let user = UserTool.getUser() else { // 取
            print("归档失败")
            return
        }
        print("id:\(user.id)\n名字:\(user.name)\n年龄:\(user.age)\n电话:\(user.phone)")
  • 运行结果


  • 存在问题
    使用案例:在ModelidInt类型,这里给的是String类型

        let dict = [
            "id" : "2",
            "name" : "隔壁老王",
            "age" : 31,
            "phone" : "110"
            ] as [String : Any]
        guard let json = dict.hw_toJSONString() else {
            print("出错")
            return
        }
        UserTool.saveUser(json) // 存

报错:主要是Codable必须是指定类型的才能转换,不然会出现以下错误

typeMismatch(Swift.Int, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "id", intValue: nil)], debugDescription: "Expected to decode Int but found a string/data instead.", underlyingError: nil))

以下方法主要是利用Codable来完成JsonModel
  • 自定义Error
enum HWMapError: Error {
    case jsonToModelFail    //json转model失败
    case jsonToDataFail     //json转data失败
}
  • 定义HWMappable协议继承Codable
public protocol HWMappable: Codable {
    func hw_modelMapFinished()
    mutating func hw_structMapFinished()
}

extension HWMappable {
    public func hw_modelMapFinished() {
        //外部自己实现
    }
    public mutating func hw_structMapFinished() {
        //外部自己实现
    }
    ///JSON转模型
    static func hw_mapFromJson(_ JSONString : String, _ type:T.Type) throws -> T {
        guard let jsonData = JSONString.data(using: .utf8) else {
            throw HWMapError.jsonToDataFail
        }
        let decoder = JSONDecoder()
        do {
            let obj = try decoder.decode(type, from: jsonData)
            var vobj = obj
            let mirro = Mirror(reflecting: vobj)
            if mirro.displayStyle == Mirror.DisplayStyle.struct {
                vobj.hw_structMapFinished()
            }
            if mirro.displayStyle == Mirror.DisplayStyle.class {
                vobj.hw_modelMapFinished()
            }
            return vobj
        } catch {
            print(error)
        }
        throw HWMapError.jsonToModelFail
    }
}

自动归档
@objcMembers class UserInfo: NSObject, NSCoding, HWMappable {
    var id: Int = 0 // 用户id
    var name: String = ""
    var phone: String = ""
    var age = 0
    /// json转模型
    class func jsonToUser(_ json:String) -> UserInfo? {
        let user = try? UserInfo.hw_mapFromJson(json, UserInfo.self)
        return user
    }

    // MARK: - 归档
    func encode(with aCoder: NSCoder) {
        UserTool.removeUser() // 归档前先删除原来的 避免错误
        for name in getAllPropertys() {
            let value = self.value(forKey: name) 
            if (value == nil) { continue }
            aCoder.encode(value, forKey: name)
        }
    }
    // MARK: - 解档
    internal required init?(coder aDecoder: NSCoder){
        super.init()
        for name in getAllPropertys() {
            let value = aDecoder.decodeObject(forKey: name) 
            if (value == nil) { continue }
            setValue(value, forKeyPath: name)
        }
    }
    // MARK: - 获取属性数组
    func getAllPropertys() -> [String] {
        var count: UInt32 = 0 // 这个类型可以使用CUnsignedInt,对应Swift中的UInt32
        let properties = class_copyPropertyList(self.classForCoder, &count)
        var propertyNames: [String] = []
        for i in 0..是可变指针,因此properties就是类似数组一样,可以通过下标获取
                let name = property_getName(property)
                // 这里还得转换成字符串
                let strName = String(cString: name)
                propertyNames.append(strName)
            }
        }
        // 不要忘记释放内存,否则C语言的指针很容易成野指针的
        free(properties)
        return propertyNames
    }
}

使用工具
class UserTool {
    // MARK: - 归档路径设置
    static private var Path: String {
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
        return (path as NSString).appendingPathComponent("account.plist")
    }

    /// 是否登录
    static func isLogin() -> Bool {
        guard UserTool.getUser() != nil else {
            return false  //文件不存在
        }
        return true
    }
    /// 存档
    static func saveUser(_ json: String) {
        guard let user = UserInfo.jsonToUser(json) else {
            return
        }
        NSKeyedArchiver.archiveRootObject(user, toFile: Path)
    }
    /// 获取用户信息
    static func getUser()-> UserInfo? {
        let user = NSKeyedUnarchiver.unarchiveObject(withFile: Path) as? UserInfo
        return user
    }
    /// 删档
    static func removeUser() {
        if FileManager.default.fileExists(atPath: Path) {
            try! FileManager.default.removeItem(atPath: Path) // 删除文件
        }else{

        }
    }
}

// MARK: - 字典转json
extension Dictionary {
    public func hw_toJSONString() -> String? {
        if (!JSONSerialization.isValidJSONObject(self)) {
            print("dict转json失败")
            return nil
        }
        if let newData : Data = try? JSONSerialization.data(withJSONObject: self, options: []) {
            let JSONString = NSString(data:newData as Data,encoding: String.Encoding.utf8.rawValue)
            return JSONString as String? ?? nil
        }
        print("dict转json失败")
        return nil
    }
}
// MARK: - json转字典
extension String {
    func hw_toDictionary() -> NSDictionary? {
        guard let jsonData:Data = self.data(using: .utf8) else {
            return nil
        }
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as? NSDictionary
        }
        return nil
    }
}

Demo
注意:Demo中有个坑,for循环中return要改成continue,不然碰到nil,直接出去不执行了 正文已经修改
参考

你可能感兴趣的:(Swift-自动归档(改进))