Objective-C 中的作用域规则非常简单。每当您输入一对大括号时,您就进入了一个新的范围级别。在该范围内声明的任何变量仅存在于该范围内。当退出大括号时,变量将不再存在。
switch 内的各个 case 不需要大括号,因此它们不定义本地级别的范围,而是定义整个 switch 语句does使用大括号,因此它确实定义了局部范围。在 switch 语句的大括号内声明的任何变量都不存在于大括号外。
当您进入新级别的范围时,您可以访问父范围中声明的所有内容。
你没有完全清楚你想做什么。我THINK
您想要做的是拥有父类的变量,然后将来自子类的新对象放入其中,并且仍然可以访问子类的独特属性。
如果声明基类的变量,则可以将该类型的子类的任何对象分配给该变量。
如果您想访问子类的属性,则必须将变量转换为适当的类型:
UIView *control = nil;
switch (objectType)
{
case label:
control = [[UILabel alloc] init]; //no error
((UILabel *)control).text = @"Something...";
break;
case button:
control = [UIButton buttonWithType: UIButtonTypeSystem];
[((UIButton *)control) setTitle: "Foo" forState: UIControlStateNormal];
default:
break;
}
EDIT
我发现强制转换语法输入起来很痛苦,而且可能会让人感到困惑。有时,创建对象实际类型的新临时变量,执行您需要执行的任何操作,然后将其分配给目标变量会更清楚,如下所示:
UIView *control = nil;
switch (objectType)
{
case label:
UILabel *aLabel = [[UILabel alloc] init]; //no error
aLabel.text = @"Something...";
aLabel.someOtherProperty = someOtherValue;
control = aLabel;
break;
case button:
UIButton aButton = [UIButton buttonWithType: UIButtonTypeSystem];
[aButton setTitle: "Foo" forState: UIControlStateNormal];
control = aButton
default:
break;
}
在 switch 语句之外,您将不知道控制变量包含哪种类型的对象,因此您只能访问 UIView 基类的属性,unless您将变量转换为特定类型,如上所示。
(请注意,上面的名称“control”是一个糟糕的选择,因为标签不是控件。最好使用“aView”之类的名称,它暗示变量中可能存在的所有对象的公共类。)