IOS serialization and deserialization
Opening
1. What is the purpose of serialization?
An object-oriented program creates a complex object graph during running. It is often serialized in binary mode. This process is called archiving. binary streams can be written to files through the network (a passage from a textbook)
I understand that when you write data that requires local storage and write your data to the hard disk, you must serialize it and convert it to a binary file, in this way, data can be read and written easily on disks. Similarly, data must be deserialized during retrieval so that data can be read out, just like encryption and decryption.
2. Why is there no serialization when I write data to plist and store it on a local disk?
Have you found that plist data is of limited type, so there are several specific data types, nsstring, have you ever tried to put a defined class (written into plist) and read it?
You can guess the result first.
In fact, the Protocol <nscoding> has been added to the nsstring class definition, which implements the nscoding proxy method.
@ Interface nsstring: nsobject <nscopying, nsmutablecopying, nscoding>
In-depth
3 nscoder and nscoding
Nscoding is a protocol, mainly including the following two methods
-(ID) initwithcoder :( nscoder *) coder; // read data from the coder and save it to the corresponding variable, that is, deserialization data
-(Void) encodewithcoder :( nscoder *) coder; // read instance variables and write the data to the coder. Serialized data
Nscoder is an abstract class. An abstract class cannot be used as an instance. It can only provide methods to inherit subclass.
Nskeyedunarchiver reads objects from binary streams.
Nskeyedarchiver writes the object to the binary stream.
4. A simple example
Generally, you need to add <nscoding> to the. h file in your own defined class.
Implement two proxy methods in the. M file. This proxy method will be automatically called.
-(Void) encodewithcoder :( nscoder *) ACO
{
[Ecoder encodeobject: Self. insuresolutionid forkey: @ "personname"];
[Ecoder encodeobject: Self. insuresolutionname forkey: @ "personage"];
}
-(ID) initwithcoder :( nscoder *) adecoder
{
Self = [Super init];
If (Self)
{
Self. insuresolutionid = [adecoder decodeobjectforkey: @ "personname"];
Self. insuresolutionname = [adecoder decodeobjectforkey: @ "personage"];
}
Return self;
}
The above is the serialization and deserialization of this class.
Nsdata * archivecarpricedata = [nskeyedarchiver archiveddatawithrootobject: Self. dataarray];
[[Nsuserdefaults standarduserdefaults] setobject: archivecarpricedata forkey: @ "dataarray"];
Nsdata * myencodedobject = [[nsuserdefaults standarduserdefaults] objectforkey: @ "dataarray"];
Self. datalist = [nskeyedunarchiver unarchiveobjectwithdata: myencodedobject];