首页 > 其他 > 详细

浅谈runtim的归档和解档

时间:2016-04-09 13:48:16      阅读:206      评论:0      收藏:0      [点我收藏+]

自定义一个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

 

浅谈runtim的归档和解档

原文:http://www.cnblogs.com/layios/p/5371367.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!