So far, I have seen two methods of serialization implemented by OC: nskeyedarchiver and nspropertylistserialization.
In both serialization methods, nsdata is the target of serialization. The difference between the two methods is that nspropertylistserialization is only for the dictionary type, while nskeyedarchiver is for the object. (In Mac OS, nsarchiver can be used to obtain more streamlined binary serialized content, but nsarchiver is not supported in IOS ).
First, let's talk about nspropertylistserialization. This is relatively simple. You only need to create an nsdictionary and then call nspropertylistserialization datafrompropertylist to write the content to nsdata. To read data, call propertylistfromdata.
Nsstring * filepath = @"..."; // Omitted. nsstring * err; // Initialization is not required. If an error occurs, it will be copied. Nsdictionary * props = [nsdictionary dictionarywithobjectsandkey: @ "Lucy", @ "name", @ "Beijing, China", @ "city", @ "supervior", @ "position ", @ "qitiandasheng", @ "company", nil]; nsdata * Data = [nspropertylistserialization datafrompropertylist: propsformat: nspropertylistxmlformat_v1_0 errordescription: & err]; if (! Err) {[data writetofile: filepath atomically: Yes]; // Write File} else {nslog (@ "error with: % @", err );}
Then let's take a look at nskeyedarchiver. From BasicCodeThe example is also very simple:
Person * Lucy = [[person alloc] initwithname: @ "Lucy"]; Lucy. address = @ "Beijing, China"; nsdata * Data = [nskeyedarchiver archivedatawithrootobject: Lucy]; [data writetofile: filepath];
The nscoding Protocol is required for the person class. The nscoding protocol contains two required methods: initwithcoder and encodewithcoder. refer to the implementation of the following two methods:
-(Void) encodewithcoder :( nscoder *) acder {[acder encodingobject: [nsnumber numberwithint: Self. age] forkey @ "Age"];}-(ID) initwithcoder :( nscoder *) adecoder {If (Self = [Super init]) {self. age = (INT) [(nsnumber *) [adecoder decodeobjectforkey: @ "Age"] intvalue] ;}return self ;}
Here, we use int age as an example of the serialization attribute to introduce another topic, namely, processing the basic type during serialization. Nscoder cannot store basic types, including int, float, and char. To serialize these attributes, they must be encapsulated.
There are two methods for encapsulation. For the basic numeric type, use the encapsulation provided by cocoa to enable nsnumber. For struct with fixed length, divide the situation. If all types of struct are fixed length and no struct type exists in the member, nsvalue can be directly used for encapsulation; otherwise, you need to write key-value by yourself. Char * should be directly encapsulated using nsstring.