Nick Ginanto
Nick Ginanto

Reputation: 32170

How to use metaprogramming in Objective-c

I have a bunch of UILabels which I named by the week days (SundayLabel, MondayLabel, etc)

I have information per day in a dictionary of the day number as a key and some text as the value

0 => "info for sunday"
1 => "info for monday"
...
6 => "info for saturday"

Since all labels are structured the same, how can I make one method that would put the info for a day to the correct label

-(void)setTextForDay:(NSinteger)dayNum{

?

}

In ruby I know I can do something like

self.send("#{Date::DAYNAMES[0]}Label=", "info for sunday")

Upvotes: 1

Views: 538

Answers (1)

Sulthan
Sulthan

Reputation: 130132

To be honest, there are ways to do this in Obj-C because Obj-C has a very good reflection. For instance, if you realize that every property has a getter (and I am assuming you are actually using @property for your labels), you can do:

NSString *getterName = [NSString stringWithFormat:@"%@Label", dayName];
SEL getterSelector = NSSelectorFromString(getterName);
UILabel *dayLabel = [self performSelector:getterSelector];

(you will probably get some ARC warnings).

However, what you have cannot be considered as good code. It's unnecessarily complicated. Usually, you would use an array

NSArray *dayLabels = @[self.mondayLabel, ..., self.sundayLabel];
UILabel *dayLabel = dayLabels[dayNum];

There is actually no need to keep the labels as separate variables. You can define an enum

typedef NS_ENUM(NSInteger, Day) {
    Monday = 0,
    ...
    Sunday
};

and index using self.dayLabels[Monday]. It's equally readable and simpler to use.

Upvotes: 3

Related Questions