1 , overview
The Nskeyedarchiver archive and the plist file store are different Nskeyedarchiver can save objects directly . If the object is NSString, Nsdictionary, Nsarray, NSData, NSNumber and other types, you can archive and restore directly with Nskeyedarchiver. Not all objects can be archived directly in this way, only objects that adhere to the nscoding protocol can be stored.
2 methods in the Nscoding protocol:
( 1 ) Encodewithcoder:
This method must be implemented when the object is stored , and this method is called each time the object is archived. In this method, you typically specify how to archive each instance variable in an object, and you can use the Encodeobject:forkey: method to archive instance variables. That is, you specify which properties are stored and what names are stored in the file as key to store these properties. For example:
[Encode encodeobject:_name forkey:@ "name"];
The next time the system takes the value of the _name from the file, it will automatically use the name of the key to fetch, followed by the Initwithcoder method to assign value to _name. In a similar way:
[Encode encodeint:_age forkey:@ "age"];
( 2 ) Initwithcoder:
The method must be implemented when the object is taken , and this method is called every time the object is recovered (decoded) from the file. In this method, you typically specify how to decode the data in a file as an instance variable of an object, and you can use the Decodeobjectforkey method to decode the instance variable. That is, specify which object in the read file becomes a property. For example:
-(ID) initwithcoder:nscoder *) decoder
{
if (self = [super init]) {
_name = [Decoder decodeobjectforkey:@ "name"];
}
return self;
}
2 , archiving Nsarray
Archive a Nsarray object to documents/array.archive:
Where the extension can be any write, do not write or can.
Nsarray *array = [Nsarray arraywithobjects:@ "a", @ "B", nil];
[nskeyedarchiver archiverootobject: Array tofile:p Ath];
Archive success will be as follows:
3 , Recovery ( decode ) Nsarray Object
4 , archived object Attention
if the parent class also follows the nscoding Agreement , please note:
(1) A sentence should be added to the Encodewithcoder: method
[Super Encodewithcode:encode];
Ensure that inherited instance variables can also be encoded, which can also be archived
(2) A sentence should be added to the Initwithcoder: method
self = [super Initwithcoder:decoder];
Ensure that inherited instance variables can also be decoded, which can also be restored
The nskeyedarchiver of data storage for Iosios development