Runtime-实现NSCoding的自动归档和自动解档
需要自定义模型持久化的时候我们往往需要为各个模型实现对应的encode``decode方法
借助Runtime我们可以对此进行封装
解档
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| - (instancetype)initWithCoder:(NSCoder *)aDecoder{ if (self = [super init]) { Class c = self.class; while (c && c != [NSObject class]) { unsigned int count = 0; Ivar *ivars = class_copyIvarList(c, &count); for (int i = 0; i < count; i++) { NSString *key = [NSString stringWithUTF8String:ivar_getName(ivars[i])]; id value = [aDecoder decodeObjectForKey:key]; if (value){ [self setValue:value forKey:key]; } } c = [c superclass]; free(ivars); } } return self; }
|
这里需要注意的是如果版本升级后Model的属性发生了变化这里可能会发生崩溃
所以需要在swtValueForKey的时候做判断
解档
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| - (void)encodeWithCoder:(NSCoder *)aCoder{ Class c = self.class; while (c && c != [NSObject class]) { unsigned int count = 0; Ivar *ivars = class_copyIvarList(c, &count); for (int i = 0; i < count; i++) { Ivar ivar = ivars[i]; NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)]; id value = [self valueForKey:key]; if (value){ [aCoder encodeObject:value forKey:key]; } } c = [c superclass]; free(ivars); } }
|