开发者

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!


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜