归档、解档

1.创建类 ZFPerson,遵循协议 NSCoding

@interface ZFPerson : NSObject

@property(strong ,nonatomic) NSString *name;

@property(assign ,nonatomic) int age;

@end


2.ZFPerson类实现协议方法

- (void)encodeWithCoder:(NSCoder*)aCoder{

    //存储成员变量个数

    unsigned int count =0;

    //获取成员变量

    Ivar*vars = class_copyIvarList([self class], &count);

    //遍历成员变量

    for(int i =0; i < count; i++) {

        Ivarivar = vars[i];

        //变量名

        const char * name = ivar_getName(ivar);

        //变量名转成utf-8

        NSString * key = [NSString stringWithUTF8String:name];

        //获取value

        id value = [self valueForKey:key];

        [aCoder encodeObject:value forKey:key];

    }

    //释放

    free(vars);

}

- (instancetype)initWithCoder:(NSCoder*)aDecoder{

    if(self= [super init]) {

        //存储成员变量个数

        unsigned int count =0;

        //获取成员变量

        Ivar * vars = class_copyIvarList([self class], &count);

        //遍历成员变量

        for(int i =0; i < count; i++) {

            Ivar ivar = vars[i];

            //变量名

            const char * name = ivar_getName(ivar);

            //变量名转成utf-8

            NSString * key = [NSString stringWithUTF8String:name];

            //获取value

            id value = [aDecoder decodeObjectForKey:key];

            [self setValue:value forKey:key];

        }

        //释放

        free(vars);

    }

    return self;

}


3.调用

- (void)archive{

    ZFPerson *p = [ZFPerson new];

    p.name=@"Cat";

    p.age=18;

    //归档路径

    NSString *path = [NSString stringWithFormat:@"%@/archiver.plist",NSHomeDirectory()];

    //归档

    [NSKeyedArchiver archiveRootObject:p toFile:path];

    //解档

    ZFPerson *p2 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

    NSLog(@"name=%@,age=%d",p2.name,p2.age);

}

你可能感兴趣的:(归档、解档)