z最近的项目有个需求,类似一只股票有多个属性和属性值,而这些属性值在后台是通过键值对来返回的,所以这时候去写正常的model就很难满足需要。我的做法是这样子的
-(void)setModel:(FundbasicinfoModel *)model integer:(NSInteger)integer{
NSArray *keyValueArr = @[@{@"基金名称":@"fundName"},@{@"数据更新日期":@"tdate"},@{@"基金类型":@"fundType"},@{@"风险等级":@"fundRiskLvl"},@{@"近一周排名":@"weekRank"},@{@"申购起点金额":@"purchMin"},@{@"申购增加金额":@"purSubMin"},@{@"晨星评级":@"cxr3"},@{@"申购日期":@"subDate"}];
NSDictionary *fundtypeDic = @{@"201":@"股票型基金",@"202":@"混合型基金",@"203":@"债券型基金",@"204":@"货币型基金",@"205":@"保守型基金",@"206":@"其他型基金",@"999":@"指数型基金",@"601":@"QDII型基金"};
NSDictionary *dic1 = keyValueArr[integer];
self.keyLabel.text = dic1.allKeys[0];
NSString *valueStr = dic1.allValues[0];
NSDictionary *dic2 = [model yy_modelToJSONObject];
if (integer == 2) {
self.valueLabel.text = [fundtypeDic objectForKey:[dic2 objectForKey:valueStr]];
}else{
self.valueLabel.text = [dic2 objectForKey:valueStr];
}
}
当然我的服务器返回的是英文的字符串,我在页面展示的时候要替换成对应的中文,这里写了一个字典来映射。然后通过键值然后再返回value值;
另外在博客园看到一位仁兄也写了一篇关于此的文章。他的举例很是形象:
有一个对象,比如说是仓库清单:model。苹果:100斤,香蕉:50斤,梨子:80斤。。。。。。。。(共50种货物)
现在我要建立一个tableView表格,一个分区,50个单元格,每个cell的内容是:货物种类 存有多少
cell肯定是根据IndexPatch.row来取值的,row对应的数组便是kindArr:["苹果","香蕉","梨子",......](长度为50)
在cell的代理函数中,我们不可能这么写:lable.text = model.kindArr[IndexPatch.row],绝对报错,问题就来了,如何把字符串转化成对象的属性呢?这个问题估计找很久都是竹篮打水。
对!你是无法通过一个占位的字符串直接点出model的属性值的,即使这个占位符代表的是model的属性值;
另附获取model全部属性的方法 ,当然并用不到,一般服务器返回的json可以直接使用,这种情况不用转换成model
//获取对象的所有属性
- (NSArray *)getAllProperties
{
u_int count;
objc_property_t *properties =class_copyPropertyList([self class], &count);
NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];
for (int i = 0; i<count; i++)
{
const char* propertyName =property_getName(properties[i]);
[propertiesArray addObject: [NSString stringWithUTF8String: propertyName]];
}
free(properties);
return propertiesArray;
}
//Model 到字典
- (NSDictionary *)properties_aps
{
NSMutableDictionary *props = [NSMutableDictionary dictionary];
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList([self class], &outCount);
for (i = 0; i<outCount; i++)
{
objc_property_t property = properties[i];
const char* char_f =property_getName(property);
NSString *propertyName = [NSString stringWithUTF8String:char_f];
id propertyValue = [self valueForKey:(NSString *)propertyName];
if (propertyValue) [props setObject:propertyValue forKey:propertyName];
}
free(properties);
return props;
}