美文网首页
swift归档解档

swift归档解档

作者: 木头炫 | 来源:发表于2022-05-19 15:51 被阅读0次

一 .遵守NSSecureCoding协议

二.实现协议方法 static var supportsSecureCoding: Bool 设置为true

      实现func encode(withcoder: NSCoder) 和requiredinit?(coder: NSCoder)

三 使用NSKeyedArchiver和NSKeyedUnarchiver进行归档解档操作

下面是代码实现:

//

//  Person.swift

//  TestSwift

//

//  Created by 李功骄 on 2022/4/22.

//

importFoundation

classPerson:NSObject,NSSecureCoding {//


    static var supportsSecureCoding: Bool {

        return true

    }


    required override init() {

        super.init()

    }


    funcencode(withcoder: NSCoder) {

        coder.encode(name, forKey:"name")

        coder.encode(age, forKey:"age")

    }

    requiredinit?(coder: NSCoder) {

        name = coder.decodeObject(forKey:"name")as?String

        age = coder.decodeObject(forKey:"age")as?Int

    }


    letfilePath:String= {

        letpath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask,true).first!asNSString

        letfilePath = path.appendingPathComponent("test.data")

        returnfilePath

    }()


    varage:Int? =0

    varname:String?



    func saveAccount() {

        letdata =try? NSKeyedArchiver.archivedData(withRootObject:self, requiringSecureCoding:true)

        try? data?.write(to: URL(fileURLWithPath:filePath))

    }


    funcloadAccount()  -> Person?{

        ifletdata =try? Data(contentsOf: URL(fileURLWithPath:filePath)) {

            letmodel =try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)as?Person

            returnmodel

        }else{

            returnnil

        }

    }

}

相关文章

网友评论

      本文标题:swift归档解档

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