Methods for using classes directly with system objects for archiving and receiving archives
Reference: http://www.cnblogs.com/BeyondAverage0908/p/4596798.html
However, for custom objects, memory errors occur when the system's class method is used for archiving and archiving, and the error message is not implemented (when archived)-(void) Encodewithcoder: (nscoder *) Acoder; method, (de-archiving) is not implemented:-(ID) Initwithcoder: (nscoder *) adecoder;
Therefore, if you need to customize the archiving and archiving of objects, you need to implement the corresponding method. Here is the Code section:
1. Create a dog class first
Dog.h
Dog.h---------------------------@interface dog:nsobject<nscoding>*name;@ Property (assign,nonatomic) Nsinteger age; @end
Note: The nscoding protocol must be implemented for the dog class because both the Encodewithcoder:acoder method and the Initwithcoder:adecoder method are defined in the Nscoding protocol.
2. Implementing methods in the Dog class
#import "Dog.h"@implementationDog- (void) Encodewithcoder: (Nscoder *) acoder{//if the parent class also adheres to the corresponding protocol, then the parent class's method should be called first to encode it (similar to the Init constructor method). //such as: [Super Encodewithcoder:acoder];[Acoder encodeObject:self.name Forkey:@"name"]; [Acoder encodeInteger:self.age Forkey:@" Age"];}- (ID) Initwithcoder: (Nscoder *) adecoder{//if the parent class also adheres to the corresponding protocol, first call the method of the parent class to decode//Self = [Super Initwithcoder:adecoder]Self.name = [Adecoder decodeobjectforkey:@"name"]; Self.age= [Adecoder Decodeintegerforkey:@" Age"]; returnSelf ;}@end
Testing in 3.main functions
Note: The methods in the corresponding protocol are automatically called during archive and archive and do not need to call the corresponding function manually
#import "Dog.h"intMainintargcConst Char*argv[]) {@autoreleasepool {//define a Dog objectDog *xiaohei =[[Dog alloc] init]; Xiaohei.name=@"Little Black"; Xiaohei.age= A; //Archive: Archive Custom dog objects to a dog.txt file in a specified directoryBOOL flag = [Nskeyedarchiver Archiverootobject:xiaohei tofile:@"/users/qianfeng/desktop/day22_oc12_ Protocol/day22_oc12_ custom Object archiving and solution archiving/dog.txt"]; if(flag) {NSLog (@"Custom Object Archive successful"); }Else{NSLog (@"Custom Object Archiving failed"); } //Archive: Extract the Dog object from the file you specifyDog *xiaohui = [Nskeyedunarchiver unarchiveobjectwithfile:@"/users/qianfeng/desktop/day22_oc12_ Protocol/day22_oc12_ custom Object archiving and solution archiving/dog.txt"]; NSLog (@"name =%@,age =%li", Xiaohui.name,xiaohui.age); NSLog (@"%@", Xiaohui); } return 0;}
Since: The archiving and archiving of custom objects has been successfully completed
Oc-archiving and unpacking of custom objects