浅谈runtim的归档和解档

自定义一个Person类

 Person.h里面

#import <Foundation/Foundation.h>

//遵循一个NSCoding协议

@interface Person : NSObject<NSCoding>

 

//定义三个person类的属性

@property(strong,nonatomic)NSString *name;

@property(assign,nonatomic)int age;

@property(strong,nonatomic)NSString *addr;

@end

 

 Person.m里面

#import "Person.h"

#import <objc/runtime.h>

 

@implementation Person

 

//实现编码方法

-(void)encodeWithCoder:(NSCoder *)aCoder

{

    unsigned int count;

    //获取指向当前类的所有属性的指针

    objc_property_t *properties=class_copyPropertyList([self class], &count);

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

    {

        //获取指向当前类的一个属性的指针

        objc_property_t property=properties[i];

        //获取C字符串属性名

        const char *name=property_getName(property);

        //C字符串转OC字符串

        NSString *propertyName=[NSString stringWithUTF8String:name];

        //通过关键字取值

        NSString *propertyValue=[self valueForKey:propertyName];

        //对属性进行编码

        [aCoder encodeObject:propertyValue forKey:propertyName];

    }

    

    //释放

    free(properties);

}

 

//实现解码方法

-(instancetype)initWithCoder:(NSCoder *)aDecoder

{

    unsigned int count;

    //获取指向当前类的所有属性的指针

    objc_property_t *properties=class_copyPropertyList([self class], &count);

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

    {

        //获取指向当前类的一个属性的指针

        objc_property_t property=properties[i];

        //获取C字符串属性名

        const char *name=property_getName(property);

        //C字符串转OC字符串

        NSString *propertyName=[NSString stringWithUTF8String:name];

        //通过关键字取值

        NSString *propertyValue=[self valueForKey:propertyName];

        //对属性进行解码

        [self setValue:propertyValue forKey:propertyName];

    }

    //释放

    free(properties);

    return self;

}

 

//归档和结档

-(void)test

{

    Person *person=[[Person alloc] init];

    person.name=@"小明";

    person.age=11;

    person.addr=@"贵阳";

    

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

    [NSKeyedArchiver archiveRootObject:person toFile:path];

 

    Person *unarchiverPerson=[NSKeyedUnarchiver unarchiveObjectWithFile:path];

    NSLog(@"unarchiverPerson=%@ %@",path,unarchiverPerson);

}

@end

 

posted @ 2016-04-09 12:32  翌日晨曦  阅读(159)  评论(0编辑  收藏  举报