IOS 对象的归档与解档

归档与解档是IOS中一种序列化与反序列化的方式。对象要实现序列化需要遵循NSCoding协议,而绝大多数Foundation和Cocoa Touch类都遵循了NSCoding协议。下面看看具体的实现方式:

一、在需要归档的类中遵循归档协议:
@interface Person : NSObject
//需要归档的属性
@property (nonatomic, strong)NSString       *name;
@property (nonatomic, assign)NSInteger      age;

@end
二、在归档对象的.m方法中实现NSCoding的协议方法
方法一:普通方式实现:
- (void)encodeWithCoder:(NSCoder *)coder
{
    //告诉系统归档的属性是哪些
    [coder encodeObject:self.name forKey:@"name"];
    [coder encodeInteger:self.age forKey:@"age"];
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super init];
    if (self) {
        //解档
        self.name = [coder decodeObjectForKey:@"name"];
        self.age = [coder decodeIntegerForKey:@"age"];
    }
    return self;
}

方法二:使用runtime方法实现:
- (void)encodeWithCoder:(NSCoder *)coder
{
    //告诉系统归档的属性是哪些
    unsigned int count = 0;//表示对象的属性个数
    Ivar *ivars = class_copyIvarList([Person class], &count);
    for (int i = 0; i
三、在Controller中实现具体的存取操作
- (IBAction)save:(UIButton *)sender {
    Person *person = [[Person alloc] init];
    person.name = @"Frank";
    person.age = 18;
    
    //这里以temp路径为例,存到temp路径下
    NSString *temp = NSTemporaryDirectory();
    NSString *filePath = [temp stringByAppendingPathComponent:@"obj.data"]; //注:保存文件的扩展名可以任意取,不影响。
    NSLog(@"%@", filePath);
    //归档
    [NSKeyedArchiver archiveRootObject:person toFile:filePath];
}

- (IBAction)read:(UIButton *)sender {
    //取出归档的文件再解档
    NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"obj.data"];
    //解档
    Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    NSLog(@"name = %@, age = %ld",person.name,person.age);
}

控制台输出:
name = Frank, age = 18

你可能感兴趣的:(IOS 对象的归档与解档)