zoukankan      html  css  js  c++  java
  • 编码对象

    要被写入和读取的对象必须继承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())")

     

  • 相关阅读:
    关于C++类中的静态数据成员
    关于C++中char,sizeof,strlen,string
    C++学习笔记(7)
    C++学习笔记(6)
    C++学习笔记(指针)
    C++学习笔记(4)
    UVA 10780
    UVA 531
    HDU, 3579 Hello Kiki
    UVA, 10413 Crazy Savages
  • 原文地址:https://www.cnblogs.com/LarryBlogger/p/6186546.html
Copyright © 2011-2022 走看看