swift 对象序列化

最近用swift做一个新项目,在项目中需要用到序列化保存一点配置信息,用来在登录前进行使用。也就想到使用序列化保存这些数据:

  • 首先创建一个类,继承于NSCoding
  • 实现NSCoding的两个protocol方法
func encode(with aCoder: NSCoder) {
}

required init?(coder aDecoder: NSCoder) {
}
  • 在类中声明需要保存的属性
  • 进行序列化和反序列化

具体代码如下:

class YFConfigManage:NSObject, NSCoding {
    
    func encode(with aCoder: NSCoder) {
        aCoder.encode(apiUrl, forKey: "apiUrl")
        aCoder.encode(downloadUrl, forKey: "downloadUrl")
        aCoder.encode(uploadUrl, forKey: "uploadUrl")
    }
    
    required init?(coder aDecoder: NSCoder) {
        apiUrl = aDecoder.decodeObject(forKey: "apiUrl") as! String
        downloadUrl = aDecoder.decodeObject(forKey: "downloadUrl") as! String
        uploadUrl = aDecoder.decodeObject(forKey: "uploadUrl") as! String
        super.init()
    }
    
    
    var apiUrl: String
    var downloadUrl: String
    var uploadUrl: String
    
    override init() {
        
        // 反序列化
        let def = UserDefaults.standard
        if let data = def.object(forKey: "YFConfigData") {
            if let configData = NSKeyedUnarchiver.unarchiveObject(with: data as! Data) as? YFConfigManage {
                apiUrl = configData.apiUrl
                downloadUrl = configData.downloadUrl
                uploadUrl = configData.apiUrl
            }
        }
        super.init()
    }
    
    func configWithResponse(responseDic: Dictionary) -> Void {
        self.apiUrl = responseDic["apiUrl"] as! String
        self.downloadUrl = responseDic["downloadUrl"] as! String
        self.uploadUrl = responseDic["uploadUrl"] as! String
        
        // 序列化
        let data = NSKeyedArchiver.archivedData(withRootObject: self)
        // 存储到本地文件
        let def = UserDefaults.standard
        def.set(data, forKey: "YFConfigData")
        def.synchronize()
        
    }
    
}

你可能感兴趣的:(swift 对象序列化)