Archive and archive custom object types

Source: Internet
Author: User

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:

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.