Archive and archive custom object types
Archive and archive custom objects
To archive and unarchive a custom class, you must follow the following protocol: NSCoding.
Student. h file
#import <Foundation/Foundation.h>@interface Student : NSObject<NSCoding>@property(nonatomic,strong)NSString *name;@property(nonatomic,assign)int age;-(instancetype)initWithName:(NSString *)name AndAge:(int)age;@end
Student. m file
# Import "Student. h "@ implementation Student-(instancetype) initWithName :( NSString *) name AndAge :( int) age {self = [super init]; if (self) {_ age = age; _ name = name;} return self;} // The call is an initialization method-(instancetype) initWithCoder :( NSCoder *) aDecoder {self = [super init]; if (self) {_ name = [aDecoder decodeObjectForKey: @ "name"]; _ age = (int) [aDecoder decodeIntegerForKey: @ "age"];} return self ;} // archive call this method-(void) encodeWithCoder :( NSCoder *) acder {NSLog (@ "encodeWithCoder"); [ACO encodeObject: _ name forKey: @ "name"]; [ecoder encodeInteger: _ age forKey: @ "age"] ;}- (NSString *) description {return [NSString stringWithFormat: @ "name =%@, age = % d ", _ name, _ age] ;}@ end
Client code
# Import "ViewController. h "# import" Student. h "# define PATH [NSHomeDirectory () stringByAppendingPathComponent: @" Student. qll "] @ interface ViewController () @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; NSLog (@" % @ ", PATH ); student * stu = [[Student alloc] init]; stu. name = @ "Zhang F"; stu. age = 13; NSLog (@ "% @", stu); // archive BOOL bol = [NSKeyedArchiver archiveRootObject: stu toFile: PATH]; if (bol = 1) {NSLog (@ "" ");} // unarchive Student * stu1 = [NSKeyedUnarchiver unarchiveObjectWithFile: PATH]; NSLog (@" % @ ", stu1 );} -(void) didReceiveMemoryWarning {[super didreceivemorywarning]; // Dispose of any resources that can be recreated .} @ end
Running result: