Reputation: 404
I have made an app that shows a todo-list for certain days. There are five labels that display a string that's been saved using NSUserDefaults. The code looks something like this:
monday1.stringValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"mo1"];
monday2.stringValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"mo2"];
monday3.stringValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"mo3"];
monday4.stringValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"mo4"];
monday5.stringValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"mo5"];
There are a lot of those lines in my code and it takes up a lot of space. I wanted to make the code shorter.
Notice that in every line the key increases by one and the label title also increases by one. You can use a for loop with the objectForKey part but not with the label title. Or at least, that's what I thought. It would make my code a lot cleaner if I could just write something like this:
for(int i = 0; i < 5; i++)
monday-%i.stringValue = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"mo%i", i];
I have tried to find a way to do this but I can't find anything online. There are no sites that say how to do it, but on the other hand there are also no sites that say it's impossible.
So does anyone know how to do this? Or is it impossible? Or any alternatives?
Upvotes: 0
Views: 127
Reputation: 285079
You can’t build variable names at runtime.
As the variables represent outlets my suggestion is to use an array.
NSArray<NSTextField *> *labels = @[monday1, monday2, monday3, monday4, monday5];
for(int i = 0; i < 5; i++) {
labels[i].stringValue = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"mo%i", i+1]];
}
Alternatively declare the labels as IBOutletCollection
which creates the array on Interface Builder level.
Upvotes: 1