美文网首页
复杂对象利用runtime快速归档

复杂对象利用runtime快速归档

作者: yiangdea | 来源:发表于2018-05-17 16:01 被阅读8次

    首先,归档和反归档的对象需要遵从coding协议
    @interface YCBreakDownModel : NSObject<NSCoding>

    然后支持归档需要实现方法:
    - (void)encodeWithCoder:(NSCoder *)aCoder
    反归档需要实现:
    - (instancetype)initWithCoder:(NSCoder *)aDecoder

    利用runtime, class_copyIvarList函数, 取得ivar指向成员变量的指针,利用ivar_getName函数,取得属性名,利用kvc取得属性值

    代码

    - (void)encodeWithCoder:(NSCoder *)aCoder {
        unsigned int propertyCount;
        Ivar * ivars = class_copyIvarList([self class], &propertyCount);
        for (int i = 0; i < propertyCount; i ++) {
            Ivar ivar = ivars[i];
            NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
            [aCoder encodeObject:[self valueForKey:key] forKey:key];
        }
    }
    
    - (instancetype)initWithCoder:(NSCoder *)aDecoder {
        if (self = [super init]) {
            unsigned int propertyCount;
            Ivar * ivars = class_copyIvarList([self class], &propertyCount);
            for (int i = 0; i < outCount; i ++) {
                Ivar ivar = ivars[i];
                NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
                [self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
            }
        }
        return self;
    }
    

    相关文章

      网友评论

          本文标题:复杂对象利用runtime快速归档

          本文链接:https://www.haomeiwen.com/subject/bugbdftx.html