复杂对象利用runtime快速归档
2018-05-17 本文已影响8人
yiangdea
首先,归档和反归档的对象需要遵从coding协议
@interface YCBreakDownModel : NSObject<NSCoding>
然后支持归档需要实现方法:
- (void)encodeWithCoder:(NSCoder *)aCoder
反归档需要实现:
- (instancetype)initWithCoder:(NSCoder *)aDecoder
利用runtime, class_copyIvarList
函数, 取得ivar指向成员变量的指针,利用ivar_getName
函数,取得属性名,利用kvc取得属性值
代码
- (void)encodeWithCoder:(NSCoder *)aCoder {
unsigned int propertyCount;
Ivar * ivars = class_copyIvarList([self class], &propertyCount);
for (int i = 0; i < propertyCount; i ++) {
Ivar ivar = ivars[i];
NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
[aCoder encodeObject:[self valueForKey:key] forKey:key];
}
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
unsigned int propertyCount;
Ivar * ivars = class_copyIvarList([self class], &propertyCount);
for (int i = 0; i < outCount; i ++) {
Ivar ivar = ivars[i];
NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
[self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
}
}
return self;
}