自定义对象常规的归档和解档

实现NSCoding协议

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeBool:self.isMe forKey:@"isMe"];
    [aCoder encodeInteger:self.age forKey:@"age"];
    [aCoder encodeObject:self.name forKey:@"name"];
}

-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {
        self.isMe = [aDecoder decodeBoolForKey:@"isMe"];
        self.age = [aDecoder decodeIntegerForKey:@"age"];
        self.name = [aDecoder decodeObjectForKey:@"name"];
  }
    return self;
}

使用步骤

 //有个对象
Person *person = [[Person alloc]init];
person.isMe = YES;
person.age = 20;
person.name = @"zhangsan";
 //文件路径
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"data.plist"];
//存储  归档
[NSKeyedArchiver archiveRootObject:person toFile:filePath];
//反归档 ,解档
Person *p = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%d-%d-%@",person.isMe,person.age,person.name);

你可能感兴趣的:(自定义对象常规的归档和解档)