利用运行时 进行模型的归解档

#ifndef define_h
#define define_h

#import <objc/runtime.h>

#define DECLEAR_NSCodingMethods() \
\
- (id)initWithCoder:(NSCoder *)coder\
{\
    Class cls = [self class];\
    while (cls != [NSObject class]) {\
        /*判断是自身类还是父类*/\
        BOOL bIsSelfClass = (cls == [self class]);\
        unsigned int iVarCount = 0;\
        unsigned int propVarCount = 0;\
        unsigned int sharedVarCount = 0;\
        Ivar *ivarList = bIsSelfClass ? class_copyIvarList([cls class], &iVarCount) : NULL;/*变量列表,含属性以及私有变量*/\
        objc_property_t *propList = bIsSelfClass ? NULL : class_copyPropertyList(cls, &propVarCount);/*属性列表*/\
        sharedVarCount = bIsSelfClass ? iVarCount : propVarCount;\
        \
        for (int i = 0; i < sharedVarCount; i++) {\
            const char *varName = bIsSelfClass ? ivar_getName(*(ivarList + i)) : property_getName(*(propList + i));\
            NSString *key = [NSString stringWithUTF8String:varName];\
            id varValue = [coder decodeObjectForKey:key];\
            NSArray *filters = @[@"superclass", @"description", @"debugDescription", @"hash"];\
            if (varValue && [filters containsObject:key] == NO) {\
                [self setValue:varValue forKey:key];\
            }\
        }\
        free(ivarList);\
        free(propList);\
        cls = class_getSuperclass(cls);\
    }\
    return self;\
}\
\
- (void)encodeWithCoder:(NSCoder *)coder\
{\
    Class cls = [self class];\
    while (cls != [NSObject class]) {\
        /*判断是自身类还是父类*/\
        BOOL bIsSelfClass = (cls == [self class]);\
        unsigned int iVarCount = 0;\
        unsigned int propVarCount = 0;\
        unsigned int sharedVarCount = 0;\
        Ivar *ivarList = bIsSelfClass ? class_copyIvarList([cls class], &iVarCount) : NULL;/*变量列表,含属性以及私有变量*/\
        objc_property_t *propList = bIsSelfClass ? NULL : class_copyPropertyList(cls, &propVarCount);/*属性列表*/\
        sharedVarCount = bIsSelfClass ? iVarCount : propVarCount;\
        \
        for (int i = 0; i < sharedVarCount; i++) {\
            const char *varName = bIsSelfClass ? ivar_getName(*(ivarList + i)) : property_getName(*(propList + i));\
            NSString *key = [NSString stringWithUTF8String:varName];\
            /*valueForKey只能获取本类所有变量以及所有层级父类的属性,不包含任何父类的私有变量(会崩溃)*/\
            id varValue = [self valueForKey:key];\
            NSArray *filters = @[@"superclass", @"description", @"debugDescription", @"hash"];\
            if (varValue && [filters containsObject:key] == NO) {\
                [coder encodeObject:varValue forKey:key];\
            }\
        }\
        free(ivarList);\
        free(propList);\
        cls = class_getSuperclass(cls);\
    }\
}

#endif /* define_h */
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容