Using Object archiving in swift for local data

Source: Internet
Author: User

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

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.