美文网首页
iOS swift 之 NSKeyedArchiver的使用

iOS swift 之 NSKeyedArchiver的使用

作者: iOS刘耀宗 | 来源:发表于2021-08-01 15:53 被阅读0次

NSKeyedArchiver一般用于对象的归档和接档. 直接上代码
模型:
注意必须遵循nscoding协议

import UIKit
import HandyJSON
class WeatherModel: NSObject,HandyJSON,NSCoding {
   
    var city: String = ""
    var week: String = ""
    var air_tips: String = ""
    required override init() {}
    required init?(coder aDecoder: NSCoder) {
        city = aDecoder.decodeObject(forKey: "city") as! String
        week = aDecoder.decodeObject(forKey: "week") as! String
        air_tips = aDecoder.decodeObject(forKey: "air_tips") as! String
    }
    func encode(with coder: NSCoder) {
        coder.encode(city, forKey: "city")
        coder.encode(week, forKey: "week")
        coder.encode(air_tips, forKey: "air_tips")
    }   
}
//获取文件路径
    func getDocumentsPath(path: String) -> String? {
 //检索指定路径
//第一个参数指定了搜索的路径名称,NSDocumentDirectory表示是在Documents中寻找.NSCacheDirectory的话就是在cache文件中寻找.第二个参数限定了文件的检索范围只在沙箱内部.其意义为用户电脑主目录.也可以修改为网络主机等.最后一个参数决定了是否展开波浪线符号.展开后才是完整路径,这个布尔值一直为YES.
//该方法返回值为一个数组,在iphone中由于只有一个唯一路径(相对OC而言),所以直接取数组第一个元素即可.
        let docPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last as NSString?
        let filePath = docPath?.appendingPathComponent(path);
        print("文件路径的地址是\(docPath ?? "")")
        return filePath
    }

      //创建对象
        let model = WeatherModel()
        model.city = "重庆"
        model.air_tips = "123123"
        //归档
        do {
            let data = try NSKeyedArchiver.archivedData(withRootObject: model, requiringSecureCoding: false)
            try data.write(to: URL(fileURLWithPath: getDocumentsPath(path: "model")!))
        } catch {
            print(error)
        }
        //解档
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: getDocumentsPath(path: "model")!))
            if let model = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? WeatherModel{
                print("model===\(model)")
                print("city = \(model.city)")
            }
        } catch {
            print("unarchive failure in init")
        }
打印结果.png

相关文章

网友评论

      本文标题:iOS swift 之 NSKeyedArchiver的使用

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