基本概念
自定义对象要支持归档,需要实现NSCoding协议
NSCoding协议有两个方法,encodeWithCoder方法对对象的属性数据做编码处理,initWithCoder解码归档数据来初始化对象
实现NSCoding协议后,就能通过NSKeyedArchiver归档
实例代码:
User.h
1 #import <Foundation/Foundation.h> 2 3 @interface User : NSObject<NSCoding> 4 5 @property(nonatomic,copy)NSString *name; 6 @property(nonatomic,copy)NSString *email; 7 @property(nonatomic,assign)NSInteger age; 8 9 @end
User.m
#import "User.h" #define AGE @"age" #define NAME @"name" #define EMAIL @"email" @implementation User //对属性编码,归档时调用 - (void)encodeWithCoder:(NSCoder *)aCoder{ [aCoder encodeInteger:_age forKey:AGE]; [aCoder encodeObject:_name forKey:NAME]; [aCoder encodeObject:_email forKey:EMAIL]; } //对属性解码,解归档时调用 - (id)initWithCoder:(NSCoder *)aDecoder{ if (self = [super init]) { _age = [aDecoder decodeIntegerForKey:AGE]; self.name = [aDecoder decodeObjectForKey:NAME]; self.email = [aDecoder decodeObjectForKey:EMAIL]; } return self; } @end
main.m
#import <Foundation/Foundation.h> #import "User.h" int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... NSLog(@"Hello, World!"); //归档 // User *user = [[User alloc] init]; // user.name = @"Warlock"; // user.email = @"warlock@wow.com"; // user.age = 1; // // NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"user.txt"]; // if ([NSKeyedArchiver archiveRootObject:user toFile:path]){ // NSLog(@"创建成功"); // } //解归档 NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"user.txt"]; User *user = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; NSLog(@"%@",user.name); } return 0; }
先将 解归档 注释起来,运行归档, 然后注释 归档 ,在运行解归档