runtime 实现序列化

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

    while (cls != NSObject.class) {
        //判断是本身类还是父类
        BOOL isSelfClass = NO;
        if (cls == self.class) {
            isSelfClass = YES;
        }
        
        unsigned int ivarCount = 0;
        unsigned int propVarCount = 0;
        unsigned int sharedVarCount = 0;
        //变量列表,含属性以及私有变量
        Ivar *lvarList = isSelfClass ? class_copyIvarList(cls, &ivarCount):NULL;
        objc_property_t *proplist = isSelfClass ? NULL:class_copyPropertyList(cls, &propVarCount);
        sharedVarCount = isSelfClass ? ivarCount:propVarCount;
        
        for (int i = 0; i < sharedVarCount; i++) {
            const char *varname = isSelfClass ? ivar_getName(*(lvarList + i)) : property_getName(*(proplist + i));
            NSString *key = [NSString stringWithUTF8String:varname];
            id value = [self valueForKey:key];
            NSArray *filters = @[@"superclass",@"description",@"debugDescription",@"hash"];
            if (value && [filters containsObject:key] == NO) {
                [aCoder encodeObject:value forKey:key];
            }
        }
        
        free(lvarList);
        free(proplist);
        cls = class_getSuperclass(cls);//指向父类
    }
    

}

  • (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self) {
        Class cls = self.class;
        while (cls != NSObject.class) {
            //判断是本身类还是父类
            BOOL isSelfClass = NO;
            if (cls == self.class) {
                isSelfClass = YES;
            }

            unsigned int ivarCount = 0;
            unsigned int propVarCount = 0;
            unsigned int sharedVarCount = 0;
            //变量列表,含属性以及私有变量
            Ivar *lvarList = isSelfClass ? class_copyIvarList(cls, &ivarCount):NULL;
            objc_property_t *proplist = isSelfClass ? NULL:class_copyPropertyList(cls, &propVarCount);
            sharedVarCount = isSelfClass ? ivarCount:propVarCount;

            for (int i = 0; i < sharedVarCount; i++) {
                const char *varname = isSelfClass ? ivar_getName(*(lvarList + i)) : property_getName(*(proplist + i));
                NSString *key = [NSString stringWithUTF8String:varname];
                id value = [aDecoder decodeObjectForKey:key];
                NSArray *filters = @[@"superclass",@"description",@"debugDescription",@"hash"];
                if (value && [filters containsObject:key] == NO) {
                    [self setValue:value forKey:key];
                }
            }

            free(lvarList);
            free(proplist);
            cls = class_getSuperclass(cls);//指向父类
        }
    }
    return self;
}

你可能感兴趣的:(runtime 实现序列化)