0

我有很多这样命名的按钮:

@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]

4

1 回答 1

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:.

于 2015-01-28T05:45:41.087 回答