美文网首页
iOS12 之后swift的归档,解档

iOS12 之后swift的归档,解档

作者: XC1988 | 来源:发表于2020-04-26 18:11 被阅读0次

模型类需要遵守NSObject,NSSecureCoding

/// 沙盒路径
let USER_INFO_PATH:String = NSHomeDirectory() + "/Documents/userPath.data"
class UserModel:NSObject,NSSecureCoding{
    //必须项
    static var supportsSecureCoding: Bool = true
    var name:String?
    //归档
    func encode(with aCoder:NSCoder) {
        if name != nil{
            aCoder.encode(name, forKey: "name")
        }
    }
    //解档
    required init(coder aDecoder:NSCoder) {
        name = aDecoder.decodeObject(forKey: "name") as? String
    }
}

具体的使用

//归档
do {
    if let model: UserModel = UserModel(JSON:json){
        let data:Data = try NSKeyedArchiver.archivedData(withRootObject:model, requiringSecureCoding: true)
        do {
             _ = try data.write(to: URL(fileURLWithPath: USER_INFO_PATH))
                print("写入成功")
        } catch {
             print("写入本地失败: \(error)")
        }
    }
} catch {
    print("写入本地失败: \(error)")
}

//解档
do {
    let data = try Data.init(contentsOf: URL(fileURLWithPath: USER_INFO_PATH))
    // 首次读取, 直接从沙盒获取数据, 就会为nil  所以这里需要使用as?
    let model = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? UserModel
    return model
} catch {
    print("获取data数据失败: \(error)")
}

相关文章

网友评论

      本文标题:iOS12 之后swift的归档,解档

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