views:

45

answers:

2

Hi everyone, I am using the following array:

NSMutableArray *buttonNames = [NSMutableArray arrayWithObjects:@"button1", @"button2", @"button3", nil];

I then want to loop through this array and create UIButtons with each array element as the object name, something like this:

for(NSString *name in buttonNames) {
    UIButton name = [UIButton buttonWithType:UIButtonTypeCustom];
    // ... button set up ...
}

However this doesn't work, I would hope it would give me three UIButtons called button1, button2, and button3.

Is this possible in objective-c? I'm pretty sure this is to do with a pointer/object issue, but I can't seem to find any similar examples to go by. Thanks for any answers, they will be greatly appreciated!

+2  A: 

No, you can't build variable names at runtime like that in Objective-C.

What you could do is using a dictionary if you insist on naming them:

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for(NSString *name in buttonNames) {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [dict setObject:button forKey:name];
    // ...
}

Then you could access the buttons later using their name:

UIButton *button = [dict objectForKey:@"foo"];

But most of the time you don't need to access them by name anyway and simply putting the buttons in array or other containers is sufficient.

Georg Fritzsche
+1 even though I had already typed out most of an almost identical answer when yours popped up.
JeremyP
@Jeremy: I know the feeling :)
Georg Fritzsche
Thank you for your answer, I went with St3fan's answer for this but your suggestion is very helpful too, I may well end up using it another part of my app :) thanks!
Adam
A: 

No what you try to do in the code shown makes no sense. You can do this though:

for (NSString* name in buttonNames) {
    UIButton* button = [UIButton buttonWithType: UIButtonTypeCustom];
    button.title = name;
    // TODO Add the button to the view.
}

Is that what you mean?

St3fan
Thanks for the quick response, that has worked perfectly!
Adam