使用枚举的 iPhone switch 语句

标签 iphone objective-c

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

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

- (void) switchTest:(Colors)testColor;

在我的实现文件中:

- (void) switchTest:(Colors)testColor{

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

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

}

我的代码编译正确,没有警告。 使用 RED 调用 switchTest 方法时,输出为: “红色选择”

但是一旦开关的第一行运行,应用程序就会意外退出并且没有警告/错误。

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

最佳答案

对我来说很好:

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;
}

关于使用枚举的 iPhone switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2960241/

相关文章:

iphone - Flipboard 动画

iphone - iPhone 应用程序和 Web 应用程序之间的双向同步

iphone - 最有效的图像更新方法

ios - AFNetworking 2.0 中的批量 GET 请求

objective-c - 如何在 Objective-C 中转换对象

ios - 无法在包 : 'NSBundle ERROR 中加载 NIB

iphone - 文件管理器 - 找不到文件 - Objective C

iphone - 导航栏出现在带有新 iOS7 SDK 的 View 上

ios - 如何在NSManagedContext中知道NSManagedObject的类型

ios - 根据 UITableView 调整 UIScrollView 高度