Definition of Object archive:
An object archive is an object archive that is saved as a file to disk, and used to read the contents of a file in the path saved by the file.
Using Nskeyedarichiver for archiving, nskeyedunarchiver, this way, the data is serialized and deserialized before the data is written and read.
Single object archiving, multiple object archiving, custom object archiving
Common archives are generally used in tool classes to archive immutable data, and variable data is not archived for easier use.
//1. An Object archive
NSString *homedictionary = Nshomedirectory ();// Get root directory
NSString *homepath = [homedictionary stringbyappendingpathcomponent:@ "Archiver.data"];// add stored file name
// archive tofile: path archiverootobject:id Object
[Nskeyedarchiver archiverootobject:@ " object " Tofile:homepath];
// Pick up
ID object = [nskeyedunarchiver Unarchiveobjectwithfile:homepath];
NSLog (@ "%@", object);
//2. Archive Multiple Objects
Nsmutabledata *data = [Nsmutabledata data];
// Archive
Nskeyedarchiver *archiver = [[Nskeyedarchiver alloc] initforwritingwithmutabledata:data];
int aInt = 100;
nsstring *astring = @ "I am an Apple";
Nsdictionary *adict = @{@ "a": @ "B", @ "C": @ "D"};
[Archiver encodeobject:@ (aInt) forkey:@ "AInt"];
[Archiver encodeobject: astring forkey:@ "astring"];
[Archiver encodeobject: adict forkey:@ "Adict"];
[Archiver finishencoding];
NSString *datahomepath = [Nshomedirectory () stringbyappendingpathcomponent:@ "Data.archiver"];
[Data writetofile:d atahomepath atomically:YES];
// Pick up
Nsmutabledata *mudata = [[Nsmutabledata Alloc]initwithcontentsoffile:datahomepath];
Nskeyedunarchiver *unarchiver = [[Nskeyedunarchiver alloc]initforreadingwithdata:mudata];
Nsinteger anint = [[Unarchiver decodeobjectforkey:@ "AInt"] integervalue];
nsstring *anstring = [Unarchiver decodeobjectforkey:@ "astring"];
nsdictionary *andict = [Unarchiver decodeobjectforkey:@ "Adict"];
[Unarchiver finishdecoding];
NSLog (@ "anint=%@,anstring=%@,andict=%@", @ (Anint), anstring,andict);
//3. custom Object Archiving implements the copy protocol
#import <Foundation/Foundation.h>
@interface Archivecopy: nsobject
@property (copy,nonatomic) nsstring *name;
@property (copy,nonatomic) nsstring *anage;
End
-(void) Encodewithcoder: (nscoder *) acoder{
[Acoder encodeobject:@ "name"];
[Acoder encodeobject:@ "Anage"];
}
-(ID) Initwithcoder: (Nscoder *) Adecoder {
if ( self = [Super Init]) {
_name = [Adecoder decodeobjectforkey:@ "name"];
_anage = [Adecoder decodeintegerforkey:@ "Anage"];
}
return self;
}
#pragma mark-nscoping
-(ID) Copywithzone: (Nszone *) Zone {
Archivecopy *copy = [[[ Self class] allocwithzone:zone] init];
Copy.name = [self. Name Copywithzone:zone];
Copy.anage = [self. Address copywithzone:zone];
return copy;
}
This article is from the "11204872" blog, please be sure to keep this source http://11214872.blog.51cto.com/11204872/1753172
Archiving of IOS objects