2

我正在编写一个应用程序,我希望在其中显示一个 alertView,根据是否发生某些情况显示不同的消息。如果没有任何情况匹配,则不应显示警报,并且应处理应用程序的其余部分。我的问题是我不知道该怎么做。我有以下代码:

 - (void) methodThatIsCalled {

             NSString *msg;

             if (blah) {

                 msg = @"Message A";

             }

             else if (blah blah) {

                 msg = @"Message B";

             }

             else if (blah blah blah) {

                 msg = @"Message C";

             }

             //Here is where I want to display the Alert code
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
             [alert show];

             else {

                   Do rest of the application....


             }

      }

谁能告诉我如何做到这一点,这样我只有一个显示警报的代码块,并动态地将消息字符串传递给警报,如果没有任何子句匹配,则什么都不做?

提前感谢所有回复的人。

4

2 回答 2

4
- (void) showAlertWithTitle: (NSString*) title message: (NSString*) message
{
    UIAlertView* alert= [[[UIAlertView alloc] initWithTitle: title message: message
                                                   delegate: NULL cancelButtonTitle: @"OK" otherButtonTitles: NULL] autorelease];
    [alert show];

}

//在你的函数中:

if (blah) {
    [self showAlertWithTitle:@"Error"  message:@"Message A"];
} 
 else if (blah blah) {
    [self showAlertWithTitle:@"Error"  message:@"Message B"];
}
于 2013-02-24T05:03:05.197 回答
3

您可以更改为

NSString *msg = nil;

然后添加一个 if

if (msg) { // If there is a message
    //Here is where I want to display the Alert code
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                              message:msg
                                              delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
    [alert show];
} else {
    ... // Rest of application
}
于 2013-02-24T04:56:04.477 回答