遍历/遍历目标C中类的所有属性 [英] Iterate/Loop through all properties of a class in Objective C

查看:101
本文介绍了遍历/遍历目标C中类的所有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复项:在类中遍历属性

问题是,在UITableView的每一行上都有很多UILabel,我需要将模型类的属性(当然是NSStrings)映射到标签标题.

The problem is I have number of UILabels on each row upon a UITableView and I need to map the properties of my model class (which are of course NSStrings) to the label titles.

由于有多个标签(超过12个,在我的项目中可能会增加),因此我使用了for循环来分配所有标签.但是,为了将变量映射到标签,我每次都必须为相应的标签进行硬编码.

As there are multiple labels(More than 12, and it might increase later in my project), hence I was using a for loop to allocate all the labels. But for mapping the variables to the labels I have to hard code each time for the corresponding label.

有没有办法遍历一个类的所有属性,以便我可以按顺序声明它们并以数组形式获取它们并正确地映射它.

Is there any way loop through all the properties of an class, so that I can declare them in an order and fetch them as an array and map it properly.

我已经看到并理解了上面可能的重复链接,但是它使用需要设置的开关次数来填充代码.取而代之的是,还有其他方法可以使用循环来进行简洁,更清晰的编码.

I have seen and understood the above possible duplicate link but it populates the code with as many switch cases as many times it is required to set. Instead of that is there any other alternative for concise and more clear coding using a loop.

任何帮助将不胜感激. 编码愉快.

Any help would be appreciated. Happy coding.

推荐答案

如果您在谈论UILabel,我会假设您想通过Xcode中的IB使用它们,但是您只是在代码中创建它们,因为您可以循环输入代码.

If you're talking about UILabels, I will assume you want to use them via IB in Xcode, however you're creating them in code just because you can loop in code.

如果是这样,您可以考虑使用IBOutletCollection代替IBOutlet,如下所示:

If so, you can think about using IBOutletCollection instead of IBOutlet like below:

@property (nonatomic, strong) IBOutletCollection(UILabel) NSArray *titleLabels;

此数组中的顺序与将它们添加到IB ui中的顺序相同.

the order in this array will be the same, as you add them in the IB ui.

希望,这会有所帮助.

这篇关于遍历/遍历目标C中类的所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆