runtime序列化 & 反序列化

2017-11-06  本文已影响14人  biyuhuaping
//引入头文件
#import <objc/message.h>
/*
 实现步骤
 - 动态获取成员变量
 - 便利所有成员变量
 - 动态获取成员变量名称作为key
 - 利用KVC获取或者设置value
 - 归档
 - 释放
 */
//告诉系统,归档哪些属性
- (void)encodeWithCoder:(NSCoder *)coder
{
    //利用runtime 来归档!!
    unsigned int count = 0;
    //count 需要改变所以传入&count c的常识
    //ivars 类似数组 不会越界
    Ivar * ivars = class_copyIvarList([self class], &count);
    
    for (int i = 0; i < count; i++) {
        //获取属性名作为key
        Ivar ivar = ivars[i];
        const char * name = ivar_getName(ivar);
        NSString * key = [NSString stringWithUTF8String:name];
        //获取value
        id value = [self valueForKey:key];
        //存入归档文件
        [coder encodeObject:value forKey:key];
    }
    
    //C语言里面!! 一旦遇到了copy creat new 需要释放
    free(ivars);
}
//解档
- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super init];
    if (self) {
        unsigned int count = 0;
        Ivar * ivars = class_copyIvarList([self class], &count);
        for (int i = 0; i < count; i++) {
            Ivar ivar = ivars[i];
            const char * name = ivar_getName(ivar);
            NSString *key = [NSString stringWithUTF8String:name];
            //解档
            id value = [coder decodeObjectForKey:key];
            //通过KVC 设置
            [self setValue:value forKey:key];
        }
        
        free(ivars);
    }
    return self;
}
上一篇下一篇

猜你喜欢

热点阅读