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

2021-09-07  本文已影响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)

上一篇下一篇

猜你喜欢

热点阅读