runtime-归档
数据持久化方式之一:归档
那么怎么实现归档呢?各位程序员应该都写过这样的代码
- (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:self.userPhone forKey:@"userPhone"]; [aCoder encodeObject:self.tokenId forKey:@"tokenId"]; [aCoder encodeBool:self.isUnlockGesture forKey:@"isUnlockGesture"]; [aCoder encodeDataObject:data]; } - (instancetype)initWithCoder:(NSCoder *)aDecoder { if (self = [super init]) { self.userPhone = [aDecoder decodeObjectForKey:@"userPhone"]; self.tokenId = [aDecoder decodeObjectForKey:@"tokenId"]; self.isUnlockGesture = [aDecoder decodeBoolForKey:@"isUnlockGesture"]; } return self; }
当你的数据模型不多的时候,感觉也并没有什么卵问题
但是!当你有20个属性的时候怎么办?复制粘贴40次?
class_copyPropertyList()函数,了解一下?
废话不多说,上代码
unsigned int propertyCount;
objc_property_t *properties = class_copyPropertyList([self class], &propertyCount);
for (int idx = 0; idx < propertyCount; idx++) {
objc_property_t property = properties[idx];
NSLog(@"propertyName: %s", property_getName(property));
}
free(properties);
打印结果
propertyName: userPhone
propertyName: tokenId
propertyName: isUnlockGesture
好像类型没看到?没有类型怎么归档,是不是傻。。
property_getAttributes(_property)函数在了解一下?