美文网首页
Model 转换为 字典方法

Model 转换为 字典方法

作者: 李二侠 | 来源:发表于2016-06-30 13:04 被阅读2515次

在与后台服务器的对接过程中,用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;
}

相关文章

网友评论

      本文标题:Model 转换为 字典方法

      本文链接:https://www.haomeiwen.com/subject/eqzxjttx.html