//
//  KKXMCategoryModel.m
//  Open
//
//  Created by 雷俊博 on 2020/9/22.
//  Copyright © 2020 黄江涛 . All rights reserved.
//

#import "KKXMCategoryModel.h"
#import <objc/runtime.h>

@implementation KKXMCategoryModel

-(void)encodeWithCoder:(NSCoder *)encoder
{
    unsigned int count = 0;
    Ivar * ivars = class_copyIvarList([self 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([self 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;
}
 
- (NSString *)description{
    NSLog(@"%@ %s", [self class],__func__);
    NSMutableString * descriptionStr = [[NSMutableString alloc]init];
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([self 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];
        
        // 设置到成员变量身上
         [descriptionStr appendFormat:@"{%@:%@},",key,value];
    }
    
    free(ivars);
    return descriptionStr;
}



@end
