2

有一个我想不通的最奇怪的问题。在下面的方法中,没有输入 switch 语句。当我打印出 的值时warningAlertViewType,它是正确的,但 switch 语句由于某种原因没有激活。我以前使用过同样的方法进行切换,效果很好。

有谁知道可能会导致这种情况?

+ (WarningAlertView*) warningAlertViewWithType:(WarningAlertViewType)warningAlertViewType
    {
        WarningAlertView *warningAlertView = nil;
        NSLog(@"WarningAlertViewType1: %d", warningAlertViewType);
        switch (warningAlertViewType)
        {
                NSLog(@"Test1");
            case WarningAlertViewTypeExit:                  warningAlertView = [[ExitWarningAlertView alloc] init]; break;
            case WarningAlertViewTypeFacebook:              warningAlertView = [[FacebookWarningAlertView alloc] init]; break;
            case WarningAlertViewTypeDelete:                warningAlertView = [[DeleteWarningAlertView alloc] init]; break;
            case WarningAlertViewTypePhotoLibrary:          warningAlertView = [[PhotoLibraryWarningAlertView alloc] init]; break;
            case WarningAlertViewTypeBack:                  warningAlertView = [[BackWarningAlertView alloc] init]; break;
            default: break;
        }
        NSLog(@"Test2");
        return [warningAlertView autorelease];
    }
4

1 回答 1

1

将您的 switch 语句更改为如下所示

switch (warningAlertViewType) {

 case WarningAlertViewTypeExit:
   NSLog(@"WarningAlertViewTypeExit");
   warningAlertView = [[ExitWarningAlertView alloc] init];
   break;

 case WarningAlertViewTypeFacebook:
   NSLog(@"WarningAlertViewTypeFacebook");
   warningAlertView = [[FacebookWarningAlertView alloc] init];
   break;

 case WarningAlertViewTypeDelete:
   NSLog(@"WarningAlertViewTypeDelete");
   warningAlertView = [[DeleteWarningAlertView alloc] init];
   break;

 case WarningAlertViewTypePhotoLibrary:
   NSLog(@"WarningAlertViewTypePhotoLibrary");
   warningAlertView = [[PhotoLibraryWarningAlertView alloc] init];
   break;

 case WarningAlertViewTypeBack:
   NSLog(@"WarningAlertViewTypeBack");
   warningAlertView = [[BackWarningAlertView alloc] init];
   break;

 default:
   NSLog(@"default");
   break;
}

我实际上是这样严格命名的粉丝。然后可以使用宏(我知道有些讨厌)来大大缩短它。

switch (warningAlertViewType) {

#define CASE(_type) \
case WarningAlertViewType ## _type: \
  NSLog(@"WarningAlertViewType" #_type); \
  warningAlertView = [[_type ## WarningAlertView alloc] init]; \
  break

CASE(Exit);
CASE(Facebook);
CASE(Delete);
CASE(PhotoLibrary);
CASE(Back);

default:
  NSLog(@"default");
  break;

#undef CASE

}
于 2013-04-09T22:58:26.103 回答