iOS数据持久化之数据归档遇到的问题

今天温习了一下数据持久化的知识,突然发现数据归档忘记怎么写了,于是就用swift重新温习了一下,期间还遇到两个小问题,现在记下来以便以后温习

//这里是写练习用的一个归档数据类
public class Node:NSObject,NSCoding
{
    public var nId:Int?
    public var name:String?
    
    override init() {
        
    }
    
    public func encode(with aCoder: NSCoder)
    {
        aCoder.encode(nId, forKey: "nId")
        aCoder.encode(name, forKey: "name")
    }
    
    public required init?(coder aDecoder: NSCoder)
    {
        self.nId = aDecoder.decodeObject(forKey: "nId") as? Int
        self.name = aDecoder.decodeObject(forKey: "name") as? String
    }
}
//这部分是归档数据的过程和取出归档数据的过程练习
let fileManager = FileManager.default
let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
 if let documentPath = urls.first
 {
       let dbPath = documentPath.appendingPathComponent("node.data")
       let node = Node()
       node.nId = 1000
       node.name = "Hello"
       let url = dbPath.path //在这里遇到过问题,最开始用的是absoluteString取的地址字符串,
       但发现在归档写文件的时候总是失败返回false后来经过查资料才发现是地址取错了,
       应该使用path来取
       print(url)
       let result = NSKeyedArchiver.archiveRootObject(node, toFile: url)
       print(result)
       if let model = NSKeyedUnarchiver.unarchiveObject(withFile: url) as? Node
       {
              print("mode is \(model.nId ?? 0), \(model.name ?? "")")
       }
  }

你可能感兴趣的:(iOS数据持久化之数据归档遇到的问题)