IOS serialization and deserialization
Excerpt from: http://hi.baidu.com/popln/blog/item/c3dd9302bb37e994d43f7ccb.html
Opening
1 What is the purpose of this serialization?
The object-oriented program creates a complex object graph at run time, often using binary methods to serialize the object graph, a process called archiving. A binary stream can be passed through the network or written to a file (a passage from a textbook)
My understanding is that when you write data need local storage, when your data will be written to the hard disk, you have to serialize him to the binary file, so as to facilitate the read and write on the disk, the same time when the removal must be deserialized, so that the data can be read out, like the encryption and disclosure process.
2 Why do I write data to plist when it is stored on a local disk, but I am not serialized ah?
We have found that, in fact, plist data is the type is limited, so several specific data types, nsstring, have you ever tried to put a class of their own definition (written into the plist), read it out?
The result is what we can guess first.
In fact, in the definition of NSString class has been added to the protocol <nscoding> that he is the way to implement the Nscoding proxy.
@interface Nsstring:nsobject <nscopying, nsmutablecopying, nscoding>
Depth
3 Nscoder and Nscoding
Nscoding is a protocol that has the following two main methods
-(ID) Initwithcoder: (Nscoder *) coder;//read data from coder, save to corresponding variable, that is, deserialize the data
-(void) Encodewithcoder: (Nscoder *) coder;//reads the instance variable and writes the data to coder. Serialization of data
Nscoder is an abstract class, an abstract class cannot be instantiated, and can only provide some methods that you want the subclass to inherit.
Nskeyedunarchiver reads an object from a binary stream.
Nskeyedarchiver writes the object to the binary stream.
41 Simple Examples
Typically in a class that you define, you need to include <NScoding> in the. h file
In. m file implementations of his two proxy methods, this proxy method will be automatically called
-(void) Encodewithcoder: (Nscoder *) Acoder
{
[Acoder encodeobject:self. Insuresolutionid forkey:@ "PersonName"];
[Acoder 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 serialization and deserialization of the class.
NSData *archivecarpricedata = [Nskeyedarchiver archiveddatawithrootobject:self. DataArray];
[[Nsuserdefaults Standarduserdefaults] setobject:archivecarpricedata forkey:@ "DataArray"];
NSData *myencodedobject = [[Nsuserdefaults standarduserdefaults] objectforkey:@ "DataArray"];
Self.datalist = [Nskeyedunarchiver unarchiveobjectwithdata:myencodedobject];
Fashion positive and negative sequence