Object archiving is one of IOS persistence and is also very common. Now let's take a look at how Swift is implemented. Implementation points
1) The nscoding protocol must be implemented.
Import uikitlet Path = (nssearchpathfordirectoriesindomains (nssearchpathdirectory. documentdirectory, nssearchpathdomainmask. userdomainmask, true) [0] as string ). stringbyappendingstring ("user. data ") class user: nsobject, nscoding {var age: Int = 0 var name: string? Init () {super. INIT ()} Init (CODER adecoder: nscoder !) {Super. INIT () self. Age = adecoder. decodeintegerforkey ("Age") self. Name = adecoder. decodeobjectforkey ("name")? String} func encodewithcoder (ACO: nscoder !) {Aco. encodeinteger (self. age, forkey: "Age") Aco. encodeobject (self. name, forkey: "name")} class func save (User: User)-> bool {return nskeyedarchiver. archiverootobject (user, tofile: Path)} class func user ()-> User? {Return nskeyedunarchiver. unarchiveobjectwithfile (PATH)? User }}
Note:
1. Implement Init (CODER adecoder: nscoder !) The default Init () constructor will be gone, so implement the default Init () or customize other constructor methods.
2. When recovering data from a file, the returned data may be empty. Therefore, pay attention to the returned values of the method.
If anything is wrong, hope wandering (Daniel) Correction