Iterate/Loop through all properties of a class in Objective C

我只是一个虾纸丫 提交于 2019-12-30 11:07:50

问题


Possible duplicate: Looping through properties in a class

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.

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.


回答1:


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.

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

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

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

Hope, this helps.



来源:https://stackoverflow.com/questions/25423817/iterate-loop-through-all-properties-of-a-class-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!