In the project may we need to save some data to the Plist file, the following on my learning process notes, immature place please point out.
Maybe I have a class called student.
Import Uikitclass student:nsobject { var text:string var age:bool init (text:string,age:int) { Self.text = text Self.age = Age } //parse back from NSObject init (coder adecoder:nscoder) { Self.text = Adecoder.decodeobjectforkey ("Text") as! String self.age = Adecoder.decodeobjectforkey ("Age") as! Int } //encoded into Object func Encodewithcoder (acoder:nscoder) { acoder.encodeobject (text, Forkey: " Text ") acoder.encodeobject (checked, Forkey:" Age ") } }
In the Encodewithcoder method, each property is set to a keyword that is used to serialize the encoding so that we parse it back in init (coder Adecoder:nscoder)
Here are two ways to save data loaded with plist
var students:[student] = [Student] () func loadstudentsdata () {Let path = self. DataFilePath ()//Declaration File Manager Let Defaultmanager = Nsfilemanager () if Defaultmanager.fileexistsatpath (path ) {Let data = NSData (Contentsoffile:path)//decoder Let archive = Nskeyedunarchiver (forread ingwithdata:data!) Students = Archive.decodeobjectforkey ("Students") as! Array//End decode archive.finishdecoding ()} else {Savestudentsdata ()}} Func Savestudentsdata () {var data = Nsmutabledata ()//voice a file to the var archive = nskeyedarchiver (fo Rwritingwithmutabledata:data)//Arrdata The Code archive.encodeobject (students, Forkey: "Students") arch Ive.finishencoding ()//write Data.writetofile (DataFilePath (), atomically:true)}
Add the Loadstudentsdata () method to the UI when it is started, and call the Savestudentsdata () method each time you change the students array
Save information to plist file in Swift