在与后台服务器的对接过程中,用model不能直接post给后台,所以 需要将model转化为字典再post过去,这里提供一个简单的model转字典的方法,也算是我自己写项目的笔记吧。
//其中的class_copyPropertyList是runtime里面遍历一个对象属性的方法,通过这个方法可以遍历出某个对象的所有属性
-(NSMutableDictionary *)returnToDictionaryWithModel:(UserLoadingModel *)model
{
NSMutableDictionary *userDic = [NSMutableDictionary dictionary];
unsigned int count = 0;
objc_property_t *properties = class_copyPropertyList([UserLoadingModel class], &count);
for (int i = 0; i < count; i++) {
const char *name = property_getName(properties[i]);
NSString *propertyName = [NSString stringWithUTF8String:name];
id propertyValue = [model valueForKey:propertyName];
if (propertyValue) {
[userDic setObject:propertyValue forKey:propertyName];
}
}
free(properties);
return userDic;
}
网友评论