There are three ways to persist iOS data:
- Attribute list (plist, nsuserdefaults)
- Archive (Nskeyedarchiver)
- Databases (SQLite, Core Data, third-party class libraries, etc.)
Archive (aka serialization), convert objects to bytecode, save them to disk as files, and restore them by unpacking (deserializing) the program as it runs or when it is rewritten again. This article mainly introduces the swift implementation of iOS data archiving.
Archiving Foundation Framework Objects
func Archivedata () {var path:anyobject=nssearchpathfordirectoriesindomains (Nssearchpathdirectory.documentdirectory, Nssearchpathdomainmask.userdomainmask,true)[0] Var filePath=path.stringbyappendingpathcomponent ("data.archive") //Archivevar array=["Bill Gates","Steve Jobs"] if(Nskeyedarchiver.archiverootobject (array, Tofile:filepath)) {NSLog ("Archive Success")}}} func Unarchivedata () {var path:anyobject=nssearchpathfordirectoriesindomains (Nssearchpathdirectory.documentdirectory, Nssearchpathdomainmask.userdomainmask,true)[0] Var filePath=path.stringbyappendingpathcomponent ("data.archive") //Anti-archivingvar data=nskeyedunarchiver.unarchiveobjectwithfile (FilePath) asNsarray NSLog ("%@", data)}
Summary:
- Easy archiving and archiving procedures
- Only one object can be archived at a time, if multiple object archives need to be separated
- Archived objects are objects in the foundation framework
- Archive and archive any of these objects need to be archived and archived throughout the file.
- Archived files are encrypted, so the file extension is free to take
Archive Custom Data
var path=nssearchpathfordirectoriesindomains (Nssearchpathdirectory.documentdirectory, Nssearchpathdomainmask.userdomainmask,true)[0] asnsstring var filePath=path.stringbyappendingpathcomponent ("data.archive") //Archivevar data=nsmutabledata () var archiver=nskeyedarchiver (Forwritingwithmutabledata:data) archiver.encodeobject (["Bill Gates","Steve Jobs"], Forkey:"Data"); Archiver.encodeint ( +, Forkey:" Age"); Archiver.encodeobject ("Test Message", Forkey:"Tip"); Archiver.finishencoding () data.writetofile (FilePath, atomically:true) //Anti-archivingvar unarchivedata=NSData (Contentsoffile:filepath) var unarchiver=nskeyedunarchiver (forreadingwithdata:unarchivedata!) var decodedata=unarchiver.decodeobjectforkey ("Data") asnsarray var decodeage=unarchiver.decodeintforkey (" Age") var decodetip=unarchiver.decodeobjectforkey ("Tip") asnsstring NSLog ("data=%@,age=%i,tip=%@", Decodedata,decodeage,decodetip)
Summary:
- In a keyed archive, each archive field has a key value that matches the key value when it is archived
- With key archive You can store multiple objects at once
- Archived objects are objects in the foundation framework
- Archive and archive any of these objects need to be archived and archived throughout the file.
- Archived files are encrypted, so the file extension is free to take
iOS Development note-swift archiving for iOS data persistence nskeyedarchiver