美文网首页
iOS. swift 本地数据归档和解档

iOS. swift 本地数据归档和解档

作者: 我会回来的 | 来源:发表于2021-09-07 18:25 被阅读0次

    iOS. swift  本地数据归档和解档 

    userDataModel 文件

    代码:

    class MyModel: NSObject,NSCoding {

        vartextOne=""

        vartextTwo=""

        var textThree = ""

        init(testOne:String,textTwo:String,textThree:String){

            self.textOne= testOne

            self.textTwo= textTwo

            self.textThree= textThree

            super.init()

        }

        requiredinit(coder aDecoder:NSCoder){

            self.textOne= aDecoder.decodeObject(forKey:"nameOne")as!String

            self.textTwo= aDecoder.decodeObject(forKey:"nameTwo")as!String

            self.textThree= aDecoder.decodeObject(forKey:"nameThree")as!String

        }

        funcencode(with coder:NSCoder) {

            coder.encode(self.textOne,forKey:"nameOne")

            coder.encode(self.textTwo,forKey:"nameTwo")

            coder.encode(self.textThree,forKey:"nameThree")

        }

    }

    // 归档

    通过plist 文件

     var accountPath=NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!//解档 

            accountPath+="/userAccount.plist"

            letaccount =NSKeyedUnarchiver.unarchiveObject(withFile: accountPath)as?MyModel

            lettestOne = account?.textOne

            print("========\(testOne)")

    // 解档

    let model =MyModel.init(testOne:self.bValueLable?.text??"", textTwo:self.cValueLable?.text??"", textThree:self.dValueLable?.text??"")

            //获取沙盒路径

            var accountPath=NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!

            accountPath+="/userAccount.plist"

            print("路径:"+accountPath)

            NSKeyedArchiver.archiveRootObject(model, toFile: accountPath)

    通过UserDefaults  方法 归档 和 解档

    代码:

    // 存数据

    let model =MyModel.init(testOne:self.bValueLable?.text??"", textTwo:self.cValueLable?.text??"", textThree:self.dValueLable?.text??"")

    let  modelData =  NSKeyedArchiver.archivedData(withRootObject: model)

    userDefault.set(modelData, forKey: "myModel")

    // 取数据

    let myModelData = userDefault.data(forKey: "myModel")

    let myModel = NSKeyedUnarchiver.unarchiveObject(with: myModelData!) as! UserInfo

    print(myModel)

    相关文章

      网友评论

          本文标题:iOS. swift 本地数据归档和解档

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