Save information to plist file in Swift

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.