iOS 将对象的属性和属性值拆分成key、value,通过字符串key来获取该属性的值

时间:2023-03-08 21:36:35

  这篇博客光看标题或许就会产生疑问,某个对象,只要它存在某个属性,且值不是空的,不就能直接用点方法获取吗,为什么要拆分成key和value多此一举呢?下面,我用一个例子告诉大家,既然这方法是存在的,那就有它存在的价值。

有一个对象,比如说是仓库清单:model。苹果:100斤,香蕉:50斤,梨子:80斤。。。。。。。。(共50种货物)

现在我要建立一个tableView表格,一个分区,50个单元格,每个cell的内容是:货物种类    存有多少

cell肯定是根据IndexPatch.row来取值的,row对应的数组便是kindArr:["苹果","香蕉","梨子",......](长度为50)

在cell的代理函数中,我们不可能这么写:lable.text = model.kindArr[IndexPatch.row],绝对报错,问题就来了,如何把字符串转化成对象的属性呢?这个问题估计找很久都是竹篮打水。

所以这里换个思维,将对象的属性和属性值拆分成key、value,代码如下(Swift):

func getValueByKey(key:String) ->String{
let hMirror = Mirror(reflecting: model)
for case let (label?, value) in hMirror.children{
if (label == key) {
return value as! String;
}
}
return "";
}

如此,cell里的代码就是lable.text = getValueByKey(key:kindArr[IndexPatch.row])

这边顺便复制过来一份OC的代码:iOS 获取对象的全部属性、把model的所有属性和对应的值转化为字典(网址:http://blog.csdn.net/moxi_wang/article/details/50740708)

//获取对象的所有属性
- (NSArray *)getAllProperties
{
u_int count;
objc_property_t *properties =class_copyPropertyList([self class], &count);
NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];
for (int i = ; 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 = ; 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;
}