0

我尝试制作一个简单的宏来在 iOS 中创建和显示一个简单的“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");

我得到错误:

解析问题。预期的 ']'

并且错误似乎指向第二个@之前"Message"

但是,如果我只是复制粘贴宏,我不会收到此错误:

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

是否反对在宏中使用 Objective-c 结构?或者那是别的什么?

4

2 回答 2

1

你的宏的问题是两个出现messagein

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

替换为@"Message",导致

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

这会导致语法错误。

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.

于 2013-01-07T20:14:07.140 回答
0

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

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];
}
于 2013-01-07T19:56:40.703 回答