Macro compiler error

半城伤御伤魂 提交于 2019-12-13 20:07:46

问题


I tried making a quick macro for creating and showing a simple "ok" dialog box in iOS:

#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 )

If I try to use it in my code:

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

I get the error:

Parse Issue. Expected']'

And the error seems to be pointing at the second @ right before "Message".

However, if I simply copy paste the macro I do not get this error:

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

Is there something against using Objective-c constructs in macros? Or did I just do something rather stupid that I can't find


回答1:


The problem with your macro is that both occurrences of message in

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

are replaced by @"Message", resulting in

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

and that causes the syntax error.

I don't think that it is really worth defining this as a macro, but if you do, you have to use macro arguments which do not occur at places where they should not be expanded, e.g.

#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 )

or similar.




回答2:


Instead of declaring it as a macro, you can declare it as a C function instead:

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


来源:https://stackoverflow.com/questions/14202963/macro-compiler-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!