1 #import "ViewController.h"2 #import "Person.h"3 @interfaceViewcontroller ()4 5 @end6 7 @implementationViewcontroller8 9- (void) Viewdidload {Ten [Super Viewdidload]; OnePerson *P1 = [personNew]; AP1.name =@"Jackie Chan"; -P1.age = -; - //converting complex objects to NSData, archiving (serialization) theNSData *p1data =[Nskeyedarchiver ARCHIVEDDATAWITHROOTOBJECT:P1]; - - //creating paths, storing P1data -NSString *path = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) [0] stringByAppendingPathComponent:@" Person"]; +NSLog (@"%@", path); - [P1data Writetofile:path atomically:yes]; + A //reading data from a file atNSData *p2data =[NSData Datawithcontentsoffile:path]; -Person *P2 =[Nskeyedunarchiver Unarchiveobjectwithdata:p2data]; - -NSLog (@"%@,%ld", p2.name,p2.age); -P2.name =@"Bruce Lee"; -P2.age = -; in - //Archive using the archive tool toNsmutabledata *mdata =[[Nsmutabledata alloc] init]; +Nskeyedarchiver *archiver =[[Nskeyedarchiver alloc] initforwritingwithmutabledata:mdata]; - //to archive the[Archiver encodeobject:p1 Forkey:@"Person1"]; *[Archiver encodeobject:p2 Forkey:@"Person2"]; $ //End ArchivePanax Notoginseng [Archiver finishencoding]; -NSLog (@"%@", mdata); the //Anti-archiving + //anti-archiving tools ANskeyedunarchiver *unarchiver =[[Nskeyedunarchiver alloc] initforreadingwithdata:mdata]; the //for anti-archiving +Person *P3 = [Unarchiver decodeobjectforkey:@"Person1"]; -Person *P4 = [Unarchiver decodeobjectforkey:@"Person2"]; $NSLog (@"%@%ld", p3.name,p3.age); $NSLog (@"%@%ld", p4.name,p4.age); - //End anti-archive - [Unarchiver finishdecoding]; the}
1 #import <Foundation/Foundation.h>23@interface person:nsobject< Nscoding>4 @property (nonatomic,copy) NSString *name; 5 @property (nonatomic,assign) Nsinteger age; 6 @end
1 #import "Person.h"2 3 @implementation Person4 //Archiving (serialization) protocol methods, converting attributes to binary data5- (void) Encodewithcoder: (Nscoder *) Acoder6 {7[Acoder encodeObject:self.name Forkey:@"name"];8[Acoder encodeInteger:self.age Forkey:@" Age"];9 }Ten //Anti-Archive (deserialization) method to restore binary data to a property One-(Nullable Instancetype) Initwithcoder: (Nscoder *) Adecoder A { -Self =[Super init]; - if(self) { theSelf.name = [Adecoder decodeobjectforkey:@"name"]; -Self.age = [Adecoder decodeintegerforkey:@" Age"]; - - } + returnSelf ; - } + @end
Archive (archive/Reverse archive)