swift归档解档

一 .遵守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

        }

    }

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容