使用枚举的iPhone开关语句

sho*_*ker 5 iphone objective-c

我在类的头文件中定义了一个枚举:

typedef enum{
 RED = 0,
 BLUE,
 Green
} Colors;

- (void) switchTest:(Colors)testColor;
Run Code Online (Sandbox Code Playgroud)

在我的实施文件中:

- (void) switchTest:(Colors)testColor{

   if(testColor == RED){
    NSLog(@"Red selected");    
   }

   switch(testColor){
    case RED:
    NSLog(@"Red selected again !");
    break;
    default:
    NSLog(@"default selected");
    break;
   }

}
Run Code Online (Sandbox Code Playgroud)

我的代码正确编译而无需更改.使用RED调用switchTest方法时,输出为:"Red selected"

但是一旦交换机的第一行运行,应用程序就会意外退出并且没有保修/错误.

我不介意使用if/else语法,但我想了解我的错误.

Bad*_*ild 13

对我来说很好:

typedef enum{
    RED = 0,
    BLUE,
    Green
} Colors;

@interface Test : NSObject

- (void) switchTest:(Colors)testColor;
@end

@implementation Test

- (void) switchTest:(Colors)testColor {
    if(testColor == RED) {
    NSLog(@"Red selected");    
    }

    switch(testColor){
    case RED:
        NSLog(@"Red selected again !");
        break;
    default:
        NSLog(@"default selected");
        break;
    }
}
@end


int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    Test *myTest = [[Test alloc] init];

    [myTest switchTest:RED];

    [myTest switchTest:RED];

    [pool drain];
return 0;
}
Run Code Online (Sandbox Code Playgroud)


Vil*_*los 8

在我的情况下,问题是我定义了变量:

Colors *testColor; //bad
Run Code Online (Sandbox Code Playgroud)

代替:

Colors testColor; //right
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.