要被写入和读取的对象必须继承NSObject,,并且实现NSCoding
关键还要实现NSCoding 的两个必要的方法
public func encode(with aCoder: NSCoder)
public init?(coder aDecoder: NSCoder)
格式如下: // 编码的时候调用这个方法 func encode(with aCoder: NSCoder) { aCoder.encode(sno, forKey: "sno") aCoder.encode(name, forKey: "name") aCoder.encode(score, forKey: "score") } // 解码的时候调用这个方法 required init?(coder aDecoder: NSCoder) { sno = aDecoder.decodeObject(forKey: "sno") as! String name = aDecoder.decodeObject(forKey: "name") as! String score = aDecoder.decodeInteger(forKey: "score") } //新创一个demo类来测试这个归档操作 // 创建对象 let student = Student(sno: "1101", name: "maizixueyuan", score: 99) // 构造路径 let path = "\(documentsPath)/student.archive" // 归档对象 NSKeyedArchiver.archiveRootObject(student, toFile: path) // 解档操作 let object = NSKeyedUnarchiver.unarchiveObject(withFile: path) as! Student print("\(object.sno), \(object.name), \(object.score)") // 检查文件 print("\(NSHomeDirectory())")
时间: 2024-12-08 12:24:12