我有很多按钮,名字如下:
@property (weak, nonatomic) IBOutlet UIButton *Round1Num1;
@property (weak, nonatomic) IBOutlet UIButton *Round1Num2;
@property (weak, nonatomic) IBOutlet UIButton *Round1Num3;
@property (weak, nonatomic) IBOutlet UIButton *Round1Num4;
@property (weak, nonatomic) IBOutlet UIButton *Round2Num1;
@property (weak, nonatomic) IBOutlet UIButton *Round2Num2;
@property (weak, nonatomic) IBOutlet UIButton *Round2Num3;
@property (weak, nonatomic) IBOutlet UIButton *Round2Num4;
等等。
我想知道我是否可以使用stringWithFormat
或类似方法动态访问它们。
示例(如果代码错误,很抱歉!):
而不是self.Round1Num1
我可以致电self.[NSString stringWithFormat:@"Round%dNum%d", 1, 1]
答案 0 :(得分:1)
您可以使用-performSelector:
:
NSString *round2Num1ButtonAccessorSelectorStr = [NSString stringWithFormat:@"Round%dNum%d", 2, 1];
SEL selector = NSSelectorFromString(round2Num1ButtonAccessorSelectorStr);
if ([self respondsToSelector:selector])
UIButton *round2Num1Button = [self performSelector:selector];
对于上下文,[self performSelector:@selector(someSelector)]
基本上等同于self.someSelector
(在属性访问器的情况下),它解析为[self someSelector]
。所有案例实际上都调用相同的运行时函数objc_msgSend(self, someSelector)
。
具体来说,在此上下文中,我们创建一个局部变量,该变量指向由VC实例上的相应IBOutlet属性隐藏的相同引用。如果该属性不存在,则选择器(最有可能)也不会因此需要通过-respondsToSelector:
来保护无法识别的选择器异常。