问题
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