【发布时间】:2015-08-02 19:36:52
【问题描述】:
我已经阅读了关于 switch 案例的范围,即 跳转标签 等等,但是这里建议的解决方案似乎暗示添加花括号可以规避这个问题。但是,这似乎仍然不起作用:
switch (objectType) {
case label: //label is an integer constant
NSLog(@"statement before declaration");
UILabel *control = [[UILabel alloc] init]; //no error
break;
case button: //button is an integer constant
{
UIButton *control = [[UIButton alloc] init]; //no error
}
break;
default:
break;
}
// error when trying to use the *control* variable,
// Use of undeclared identifier 'control'
有什么方法可以用 switch 语句来完成这个吗?
2015 年 5 月 23 日:尝试了许多不同的方法,但都没有成功。
编辑:实施 Cyrille 建议的解决方案时出错:
UIView *control = nil;
switch (objectType)
{
case label: //button is an integer constant
{
control = [[UILabel alloc] init]; //no error
//error: property 'text' not found on object of type 'UIView *'
control.text = @"Something...";
}
break;
default:
break;
}
显然,即使从UIView重铸为UILabel,对象也没有继承UILabel的所有属性,因此报错:
在“UIView *”类型的对象上找不到属性“文本”
即使是 Zil 建议为类型添加前缀 (UILabel*)[[UILabel alloc]init]; 也没有奏效。
有人让这个工作吗?
DUNCAN C. 的解决方案 (请参阅下面接受的答案)
UIView *control = nil;
switch (objectType)
{
case label:
control = [[UILabel alloc] init];
((UILabel *)control).text = @"Something...";
break;
default:
break;
}
// UI object instantiated inside switch case recognised!
((UILabel *)control).textColor = [UIColor redColor];
谢谢邓肯 C。
【问题讨论】:
-
请注意,如果您有另一种情况,即按钮,它创建一个按钮并分配
control=button,则您在 switch 语句之外的代码将在运行时崩溃。那是因为在这种情况下,控件对象不包含标签,它包含一个按钮,如果你将它转换为 UILabel,你是在告诉编译器“相信我,它是一个标签”,但你错了。跨度> -
@Duncan C:你说的完全正确;我在发布之前也注意到了这一点,但只是想简单地表明该对象确实在 switch 块之外被识别。谢谢。
标签: ios objective-c scope switch-statement declaration