macros编译器错误

我试着在iOS中创build并显示一个简单的“OK”对话框:

#define ALERT_DIALOG(title,message) \ do\ {\ UIAlertView *alert_Dialog = [[UIAlertView alloc] initWithTitle:(title) message:(message) delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];\ [alert_Dialog show];\ } while ( 0 ) 

如果我尝试在我的代码中使用它:

 ALERT_DIALOG(@"Warning", @"Message"); 

我得到的错误:

parsing问题。 预期']'

而错误似乎指向"Message"之前的第二个@

但是,如果我只是复制粘贴macros,我不会得到这个错误:

 NSString *title = @"Warning"; NSString *message = @"Message"; do { UIAlertView *alert_Dialog = [[UIAlertView alloc] initWithTitle:(title) message:(message) delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert_Dialog show]; } while ( 0 ); 

是否有什么反对在macros中使用Objective-c结构? 还是我做了一些我找不到的蠢事

你的macros的问题是, 在两个 message中出现

 ... [[UIAlertView alloc] initWithTitle:(title) message:(message) ... 

@"Message"所取代,导致

 .... [[UIAlertView alloc] initWithTitle:(@"Warning") @"Message":(@"Message") ... 

并导致语法错误。

我不认为把这个定义为一个macros是非常有价值的,但是如果你这么做的话,你必须使用不应该扩展的地方的macros参数,例如

 #define ALERT_DIALOG(__title__,__message__) \ do\ {\ UIAlertView *alert_Dialog = [[UIAlertView alloc] initWithTitle:(__title__) message:(__message__) delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];\ [alert_Dialog show];\ } while ( 0 ) 

或类似的。

您可以将其声明为C函数,而不是将其声明为macros:

 void ALERT_DIALOG(NSString *title, NSString *message) { UIAlertView *alert_Dialog = [[UIAlertView alloc] initWithTitle:(title) message:(message) delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];\ [alert_Dialog show]; } 
    Interesting Posts