objective-c - 在 switch block 中实例化新对象 - 为什么会失败?

标签 objective-c

为什么

switch ([document currentTool]) {
    case DrawLine:
        NSBezierPath * testPath = [[NSBezierPath alloc]init];
        //...rest of code that uses testPath....

结果

错误:“*”标记前的语法错误

测试路径?

最佳答案

你不能在 case 语句中实例化一个对象,除非你把它放在一个新的范围内。这是因为否则你可以做这样的事情:

switch( ... ) {
    case A:
       MyClass obj( constructor stuff );
       // more stuff
       // fall through to next case
    case B:
       // what is the value of obj here? The constructor was never called
    ...
}

如果您希望对象在案例期间持续存在,您可以这样做:

switch( ... ) {
    case A: {
       MyClass obj( constructor stuff );
       // more stuff
       // fall through to next case
    }
    case B:
       // obj does not exist here
    ...
}

这在 Objective C 以及 C 和 C++ 中是相同的。

关于objective-c - 在 switch block 中实例化新对象 - 为什么会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/366073/

相关文章:

iphone - iPhone 上的 3G 网络电话,SDK 有何变化?

ios - UITextField 子类困惑 adjustFontSizeToWidth

objective-c - objective-c中的二进制转换算法

ios - 如何以编程方式截取 iPad 主屏幕的屏幕截图?

iphone - 如何使用 selectRowAtIndexPath 强制选择 UITableViewCell?

objective-c - 核心数据或 NSUserDefaults 以避免操纵用户?

ios - 没有 Storyboard Receiver的AMSlideMenu的问题没有标识符'rightMenu'的提示

ios - ViewController 偶尔会错过响应链?

ios - UITableViewController自定义setEditing:animated:

ios - 在 iPhone 应用程序中以美国格式显示电话号码