1 , overview
Use the Archiverootobject:tofile: method to write an object directly to a file, but sometimes you might want to write multiple objects to the same file, then use NSData to archive the object.
NSData can provide temporary storage for some data for subsequent writing to a file, or for storing the contents of a file read from disk. You can use [Nsmutabledata data] To create variable data spaces.
2 , archiving 2 a Person object into the same file
Archive (Code):
Create a new variable data area
nsmutabledata *data = [nsmutabledata data];
To connect a data area to a Nskeyedarchiver object
nskeyedarchiver *archiver = [[[nskeyedarchiver alloc] initforwritingwithmutabledata :d ATA] autorelease];
Start archive object, archived data will be stored in Nsmutabledata
[Archiver encodeobject:p erson1 forkey: @ "Person1"];
[Archiver encodeobject:p erson2 forkey: @ "Person2"];
Archive complete (Be sure to call this method)
[Archiver finishencoding];
Writing archived data to a file
[Data writetofile:p Ath Atomically:yes];
3 , recovering from the same file 2 a Person Object
Restore (decode):
Reading data from a file
NSData *data = [NSData datawithcontentsoffile:p Ath];
Parse into a Nskeyedunarchiver object based on the data
nskeyedunarchiver *unarchiver = [[nskeyedunarchiver alloc] initforreadingwithdata: Data];
Person *person1 = [Unarchiver decodeobjectforkey: @ "Person1"];
Person *person2 = [Unarchiver decodeobjectforkey: @ "Person2"];
Recovery complete
[Unarchiver finishdecoding];
4 , using archiving for deep replication
For example, a deep copy of a person object:
Temporary storage of Person1 data
NSData *data =
[nskeyedarchiver archiveddatawithrootobject:p Erson1];
Parse data to generate a new person object
Student *person2 =
[nskeyedunarchiver unarchiveobjectwithdata:d ATA];
Print memory addresses separately
NSLog (@ "person1:0x%x", Person1); Person1:0x7177a60
NSLog (@ "person2:0x%x", Person2); Person2:0x7177cf0
NSData of data storage for iOS development