Runtime 实现归档

在.h中

#import <Foundation/Foundation.h>
//pdf 基本设置的模型
@interface ScratchPDFSetModel : NSObject<NSCoding>

//颜色
@property (nonatomic, assign) CGFloat R;
@property (nonatomic, assign) CGFloat G;
@property (nonatomic, assign) CGFloat B;
//字体大小
@property (nonatomic, assign) CGFloat font;
@end

在.m中


- (void)encodeWithCoder:(nonnull NSCoder *)aCoder {
  unsigned int count = 0;
//获取变量名
  Ivar *ivars = class_copyIvarList([self class], &count);
  for (NSInteger index = 0; index<count; index++) {
      Ivar ivar = ivars[index];
      const char *name = ivar_getName(ivar);
      NSString *strName = [NSString stringWithUTF8String:name];
      
      id value = [self valueForKey:strName];
      [aCoder encodeObject:value forKey:strName];
  }
  free(ivars);
}

- (nullable instancetype)initWithCoder:(nonnull NSCoder *)aDecoder {
  if (self = [super init]) {
      unsigned int count = 0;
//        获取成员的变量名
      Ivar *ivars = class_copyIvarList([self class], &count);
      for (NSInteger index = 0; index < count; index ++) {
          Ivar ivar = ivars[index];
          const char * name = ivar_getName(ivar);
          NSString *strName = [NSString stringWithUTF8String:name];
          id value = [aDecoder decodeObjectForKey:strName];
          [self setValue:value forKey:strName];
      }
      free(ivars);
  }
  return self;
}

这么做的好处是,不在需要每个属性都实现。如果一个模型的属性多的话,使用runtime的好处就大了。

//这里的attribute 换成你们自己的属性。我这里只是一个说明
- (void)encodeWithCoder:(nonnull NSCoder *)aCoder{
[aCoder encodeObject:self. attribute forKey: @"attribute"];
}
- (nullable instancetype)initWithCoder:(nonnull NSCoder *)aDecoder{
    if (self = [super init]) {
        self. attribute =  [aDecoder decodeObjectForKey:@"attribute"];
   }
    return self;
}

在外部使用:

    //归档
     ScratchPDFSetModel *model = [ScratchPDFSetModel new];
      model.R = 1;
      model.G = 0;
      model.B = 0;
      model.font = 10;
      [NSKeyedArchiver archiveRootObject:model toFile:filePath];
//解档
      NSString *filePath = [[ScratchPdfTool     shareInstance]createPDFSetPlist];
      ScratchPDFSetModel *setModel = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容