如果想對自己自定義的類進行解檔和歸檔的話 必須遵循一個協議:NSCoding Student.h 文件 Student.m 文件 客戶端代碼 運行結果:
自定義的對象的解檔和歸檔
如果想對自己自定義的類進行解檔和歸檔的話 必須遵循一個協議:NSCoding
Student.h 文件
#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 文件
#import "Student.h" @implementation Student - (instancetype)initWithName:(NSString *)name AndAge:(int)age { self = [super init]; if (self) { _age=age; _name=name; } return self; } //解答時候調用 是一個初始化的方法 -(instancetype)initWithCoder:(NSCoder *)aDecoder{ self=[super init]; if (self) { _name=[aDecoder decodeObjectForKey:@"name"]; _age=(int)[aDecoder decodeIntegerForKey:@"age"]; } return self; } //歸檔調用該方法 -(void)encodeWithCoder:(NSCoder *)aCoder{ NSLog(@"encodeWithCoder"); [aCoder encodeObject:_name forKey:@"name"]; [aCoder encodeInteger:_age forKey:@"age"]; } -(NSString *)description{ return [NSString stringWithFormat:@"name=%@,age=%d",_name,_age]; } @end
客戶端代碼
#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=@"張F"; stu.age=13; NSLog(@"%@",stu); //歸檔 BOOL bol=[NSKeyedArchiver archiveRootObject:stu toFile:PATH]; if (bol==1) { NSLog(@"歸檔成功"); } //解檔 Student *stu1=[NSKeyedUnarchiver unarchiveObjectWithFile:PATH]; NSLog(@"%@",stu1); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
運行結果: