Adam
Adam

Reputation: 23

Use NSString as object name

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!

Upvotes: 2

Views: 887

Answers (2)

Stefan Arentz
Stefan Arentz

Reputation: 34935

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?

Upvotes: 0

Georg Fritzsche
Georg Fritzsche

Reputation: 98984

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.

Upvotes: 2

Related Questions