runtime +kvo实现快速归档 解档操作

先看一个初始版的

`

  • (void)viewDidLoad {
    [super viewDidLoad];

    Person *person = [[Person alloc]init];
    person.name = @"ezreal";
    person.height = @"134";
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

    NSString *path = [filePath stringByAppendingPathComponent:@"test.plist"];
    

    BOOL result = [NSKeyedArchiver archiveRootObject:person toFile:path];
    if (result) {
    NSLog(@"success");
    }else
    {
    NSLog(@"fail");
    }
    NSLog(@"%@",filePath);

}
`

`
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:self.height forKey:@"height"];
}

//当从文件中读取一个对象的时候就会调用方法
//在该方法中说明如何读取保存在文件中的对象

-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.height = [aDecoder decodeObjectForKey:@"height"];
}
return self;
}
`

runtime版本

`
// 返回self的所有对象名称

  • (NSArray *)propertyOfSelf{
    unsigned int count = 0;

    // 1. 获得类中的所有成员变量
    Ivar *ivarList = class_copyIvarList(self, &count);

    NSMutableArray *properNames =[NSMutableArray array];
    for (int i = 0; i < count; i++) {
    Ivar ivar = ivarList[i];

      // 获得成员属性名
      NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];
      
    [properNames addObject:key];
    

    }
    free(ivarList);
    return [properNames copy];
    }

// 归档

  • (void)encodeWithCoder:(NSCoder *)enCoder{
    // 取得所有成员变量名
    NSArray *properNames = [[self class] propertyOfSelf];

    for (NSString *propertyName in properNames) {
    [enCoder encodeObject:[self valueForKey:propertyName] forKey:propertyName];
    }
    }

// 解档

  • (id)initWithCoder:(NSCoder *)aDecoder{
    // 取得所有成员变量名
    NSArray *properNames = [[self class] propertyOfSelf];

    for (NSString *propertyName in properNames) {

      [self setValue:[aDecoder decodeObjectForKey:propertyName] forKey:propertyName];
    

    }
    return self;
    }

`

你可能感兴趣的:(runtime +kvo实现快速归档 解档操作)