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

先看一个初始版的
<pre>`

  • (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);

}
`</pre>

<pre>`
-(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;
}
`</pre>

runtime版本

<pre>`
// 返回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;
    }

`</pre>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容