使用 BOOL 作为按钮的 属性

Use BOOL as property of button

我有一个布尔值,我想将其设置为按钮的 属性:

int tag = (int)[sender tag];
NSString* keyPath = [NSString stringWithFormat:@"addButton%d.hidden", tag];
[self setValue:YES forKey:keyPath];

我不能直接这样做,因为 addButton 的号码会根据发件人的标签而变化。

我已经尝试过:

setValue:[NSNumber numberWithBool:YES]

但不起作用。

我哪里错了?

可能是setValue:forKeyPath:,取值必须是对象

[self setValue:@(YES) forKeyPath:keyPath];

这整个问题都是基于糟糕的架构。具有 addButton1addButton2addButton3 等属性首先很难处理。每次您看到自己在属性末尾添加数字时,请改用数组。

NSArray *addButtons = @[self.addButton1, self.addButton2, self.addButton3];

然后简单地

[addButtons[sender.tag - 1] setHidden:YES];

使用 KVC 仅适用于特定情况。如果您是初学者,请尽量不要使用它。过度使用它是一个坏习惯。直接访问属性,不使用字符串名称。