Objective-C中String的对象名

Ret*_*ogs 4 objective-c

我想从字符串中设置像UIButton这样的对象的名称.

NSString *buttonName = [[NSString alloc] initWithString:@"someString"];

我的目标是:

UIButton *someString = [[UIButton buttonWithType:UIButtonTypeCustom]retain];

我怎么能解决这个问题?

小智 6

你不能 - 在执行任何Objective-C代码之前,编译器很好地解析了变量名.您可以做的是使用以下方法维护字符串映射到按钮等对象NSMutableDictionary:

NSString *string = @"someString";
[buttonMap setObject: [UIButton buttonWithType:UIButtonTypeCustom] forKey: string];

//...time passes...

[[buttonMap objectForKey: @"someString"] setEnabled: YES];
Run Code Online (Sandbox Code Playgroud)