Runtime写归档方法~

runtime开源代码http://opensource.apple.com/source/objc4/objc4-493.9/runtime/

runtime是OC语言的运行时机制,OC所有的代码编译时都会编译为runtime代码

runtime可以值机操控类的方法和成员变量等等.

runtime还可以动态创建类,我们平时用的zombie调试就使用了runtime动态创建类的功能

runtime可以随意访问类的方法和成员以及类名等相关信息

我们使用runtime时一般都会使用下面两个文件

<objc/runtime.h>

<objc/message.h>

runtime中

1> Ivar : 成员变量

2> Method : 成员方法

下面的代码就可以将归档时要写的代码替换掉,因为有时候一个类可能有几十个属性,如果一行一行写encdoe方法和decode方法不但麻烦而且浪费时间

可以利用运行时机制一步到位,有兴趣的童鞋可以将下面的代码抽取成宏,这样用起来更方便

- (void)encodeWithCoder:(NSCoder *)encoder
{
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([Person class], &count);
    
    for (int i = 0; i<count; i++) {
        // 取出i位置对应的成员变量
        Ivar ivar = ivars[i];
        
        // 查看成员变量
        const char *name = ivar_getName(ivar);
        
        // 归档
        NSString *key = [NSString stringWithUTF8String:name];
        id value = [self valueForKey:key];
        [encoder encodeObject:value forKey:key];
    }
    
    free(ivars);
}

- (id)initWithCoder:(NSCoder *)decoder
{
    if (self = [super init]) {
        unsigned int count = 0;
        Ivar *ivars = class_copyIvarList([Person class], &count);
        
        for (int i = 0; i<count; i++) {
            // 取出i位置对应的成员变量
            Ivar ivar = ivars[i];
            
            // 查看成员变量
            const char *name = ivar_getName(ivar);
            
            // 归档
            NSString *key = [NSString stringWithUTF8String:name];
            id value = [decoder decodeObjectForKey:key];
            
            // 设置到成员变量身上
            [self setValue:value forKey:key];
        }
        
        free(ivars);
    }
    return self;
}

另外利用runtime机制时如果获得的runtime变量是通过含有copy字样的函数得到的,记得一定要调用free函数释放,否则就会造成内存泄露

原文地址:https://www.cnblogs.com/xyzaijing/p/3855699.html