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

时间:2008-12-14 02:06:48

标签: objective-c

为什么

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

结果

error:syntax error before "*" token

for testPath?

1 个答案:

答案 0 :(得分:10)

除非将其放在新范围内,否则无法在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 ++相同。