iOS_runtime实现NSCoding NSCoder缓存对象 NSCoping

2022-07-20 13:55:44 浏览数 (1)

<NSCoding> 

当类中包含其他类似, 其他类也实现NSCoding就行

代码语言:javascript复制
#pragma mark - 解档
- (id)initWithCoder:(NSCoder *)decoder {
  if (self = [super init]) {
    unsigned int count = 0;
    Ivar *ivar = class_copyIvarList([self class], &count);
    for (int i = 0; i < count; i  ) {
      Ivar iva = ivar[i];
      const char *name = ivar_getName(iva);
      NSString *strName = [NSString stringWithUTF8String:name];
      // 进行解档取值
      id value = [decoder decodeObjectForKey:strName];
      [self setValue:value forKey:strName];
    }
    free(ivar);
  }
  return self;
}

#pragma mark - 归档
- (void)encodeWithCoder:(NSCoder *)encoder {
  unsigned int count;
  Ivar *ivar = class_copyIvarList([self class], &count);
  for (int i = 0; i < count; i  ) {
    Ivar iv = ivar[i];
    const char *name = ivar_getName(iv);
    NSString *strName = [NSString stringWithUTF8String:name];
    id value = [self valueForKey:strName];
    // 进行归档赋值
    [encoder encodeObject:value forKey:strName];
  }
  free(ivar);
}

NSCoder 是一个抽象类,抽象类不能被实例话,只能提供一些想让子类继承的方法。

子类: NSKeyedArchiver (序列化)  从二进制流读取对象。

子类: NSKeyedUnarchiver (反序列化) 把对象写到二进制流中去。

代码语言:javascript复制
// 序列化
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [path stringByAppendingString:@"/holderModel"];
[NSKeyedArchiver archiveRootObject:_holderModel toFile:filePath];

// 反序列化
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [path stringByAppendingString:@"/holderModel"];
_holderModel = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

NSUserDefault存Model

代码语言:javascript复制
// Model 实现`NSCoding`协议
// 存
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:_standardPreferenceModel];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:kTicPods2StandardPreferenceModel];
[[NSUserDefaults standardUserDefaults] synchronize];

// 取
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:kTicPods2StandardPreferenceModel];
_standardPreferenceModel = [NSKeyedUnarchiver unarchiveObjectWithData:data];
return _standardPreferenceModel;

<NSCopying>

NSCoping好像没有什么快捷的方法, 只能一个一个copy

当类中包含其他类似, 其他类也实现NSCoping就行

代码语言:javascript复制
- (id)copyWithZone:(NSZone *)zone {
  HolderBean *holder = [[[self class] allocWithZone:zone] init];
  holder.holderId = _holderId;
  holder.choose = _choose;
  holder.avatar = [_avatar copy];
  holder.gender = [_gender copyWithZone:zone];
  holder.relation = [_relation copyWithZone:zone];
  return holder;
}

0 人点赞