Archiving refers to the process of saving one or more objects in some format for later restoration of those objects.
Archive using an XML attribute list
If you are archiving the Nsstring,nsdictionary,nsarray,nsdata,nsnumber object, you can use the Writetofile:atomically: Method implemented in the class to write the data to a file.
Use the Dictionarywithcontentsoffile or Arraywithcontentsoffile,datawithcontentsoffile,stringwithcontentsoffile method to read back the data.
Using Nskeyedarchiver archiving
Storing various types of objects in a file, not just strings, arrays, and dictionaries, has a more flexible way of nskeyedarchiver the class to create a keyed file to complete.
In a keyed file, each archived field has a name. When you archive an object, give it a name, which is the key. When retrieving an object from an archive, it is retrieved based on the key.
Coding method and decoding method
Custom class objects cannot be archived directly. Because the system does not know how to archive.
Follow the <NSCoding> protocol to add the Encodewithcoder method and the Initwithcoder method to the class to implement the archive specification.
The Encodewithcoder method tells the archiver how to archive. The Initwithcoder method tells how to encode.
The basic OC class described earlier, can be encoded using Encodeobject:forkey, Decodeobject:forkey to decode, for the basic C type use the following methods
| Encoding method |
Decoding method |
| Encodebool:forkey: |
Decodebool:forkey: |
| Encodeint:forkey: |
Decodeint:forkey: |
| Encodeint32:forkey: |
Decodeint32:forkey: |
| Encodeint64:forkey: |
Decodeint64:forkey: |
| Encodefloat:forkey: |
Decodefloat:forkey: |
| Encodedouble:forkey: |
Decodedouble:forkey: |
Here's an example:
-(void) Encodewithcoder: (Nscoder *) coder{ [coder encodeobject:@ "Tongxue" forkey:@ "name"]; [Coder encodeint:13 forkey:@ "age"];} -(ID) Initwithcoder: (Nscoder *) adecoder{ nsstring * name = [Adecoder decodeobjectforkey:@ "name"]; int age = [Adecoder decodeintforkey:@ ' age ']; return self;}
iOS Archive Learning Notes