美文网首页
runtime +kvo实现快速归档 解档操作

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

作者: 有一种再见叫青春 | 来源:发表于2016-11-07 14:24 被阅读29次

    先看一个初始版的
    <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>

    相关文章

      网友评论

          本文标题:runtime +kvo实现快速归档 解档操作

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