美文网首页Swift学习
Swift-归档解归档

Swift-归档解归档

作者: 千年一梦s | 来源:发表于2019-06-28 10:26 被阅读0次
    1.遵守NSSecureCoding协议
    2.实现协议的两个方法
     //归档解归档代理
        func encode(with aCoder: NSCoder){
            aCoder.encode(name, forKey: "name")
            aCoder.encode(age, forKey: "age")
            aCoder.encode(score, forKey: "score")
        }
        
        required init?(coder aDecoder: NSCoder){
            name = aDecoder.decodeObject(forKey: "name") as? String
            age = aDecoder.decodeObject(forKey: "age") as? NSNumber
            score = aDecoder.decodeObject(forKey: "score") as? NSNumber
        }
    
    3.自定义方法,读取和保存数据
    //路径定义
        let path =   NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask
        , true).first! as NSString
        let filePath = path.appendingPathComponent("person.plist")
    
        //保存和读取数据
        func saveAccount(){
            do {
                //归档为data数据
                let data = try NSKeyedArchiver.archivedData(withRootObject: self, requiringSecureCoding: true)
                //将数据写入文件
                try data.write(to: URL(fileURLWithPath: filePath))
                
            } catch {
                print(error)
            }
            
        }
        class func loadAccount() -> UserAccount? {
            print(filePath)
            do {
                //从本地文件读取data数据
               let data = try Data(contentsOf: URL(fileURLWithPath: filePath))
                //解档数据
               let account = try NSKeyedUnarchiver.unarchivedObject(ofClasses: [UserAccount.classForKeyedUnarchiver()], from: data) as? UserAccount
               return account
            } catch {
                print(error)
                return nil
            }
        }
    

    相关文章

      网友评论

        本文标题:Swift-归档解归档

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