或许我们会有一些这样的场景,定义一个Model类来临时存储一些数据,然后稍后再把这些数据组织成 Dictionary,再做其他用途。
可以通过运行时机制 获取类的PropertyList,然后根据 其中的某个Property找到对应的iVar,通过ivar 获取到对应的值。通过属性名作为字典键值,iVar值作为value付给Dic,至此结束。
- (NSDictionary *)dicSerializeObject
{
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:5];
NSString *className = NSStringFromClass([self class]);
id class = objc_getClass([className UTF8String]);
// 获取类中的property
unsigned int propertyCount;
objc_property_t *properties = class_copyPropertyList(class, &propertyCount);
for (unsigned int i = 0; i < propertyCount; i++)
{
objc_property_t property = properties[i];
const char *cPropertyName = property_getName(property);
// 得到属性名
NSString *propertyName = [NSString stringWithCString:cPropertyName encoding:NSUTF8StringEncoding];
// 获取实例变量
Ivar ivar = class_getInstanceVariable([self class], cPropertyName);
if (ivar == nil)
{
ivar = class_getInstanceVariable([self class], [[NSString stringWithFormat:@"_%@", propertyName] UTF8String]);
}
// 赋值
if(ivar != nil)
{
id propertyValue = object_getIvar(self, ivar);
if (propertyValue)
{
[dictionary setObject:propertyValue forKey:propertyName];
}
}
}
free(properties);
return dictionary;
}
将这个方法定义实现在NSObject的Category中,即可方便使用。
还看到这一篇博客(JSON转Model思路):http://ios.jobbole.com/82975/