Where to put common UIAlertView code

I have a password UIAlertView that we ask the user for. I need to ask it on different views depending on the scenario, from a downloadViewController (after the user downloads their data), when they switch to their data (if the user has multiple accounts, there's a password per account), and when the app awakes from sleep (from the app delegate).

I have common UIAlertView code that basically checks the database for their password and stuff. Is there a good place to put this common code? I feel like I'm copying and pasting the showing of the alert and the delegate methods for this alert. In certain view controllers, there will be other alerts as well though, and I have to respond to those through the UIAlertViewDelegate in that specific ViewController.


You may create a category like this and then just reuse the code:

*.h file

@interface UIViewController(Transitions)

- (void) showAlertWithDelegate: (id) delegate;

@end

*.m file

-(void) showAlertWithDelegate:(id)delegate {

    id _delegate = ( delegate == nil) ? self : delegate;
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle: NSLocalizedString(@"Alert Text",@"Alert Text")
                          message: NSLocalizedString( @"Msg Alert",@"Msg Alert")
                          delegate:_delegate 
                          cancelButtonTitle:nil
                          otherButtonTitles: NSLocalizedString(@"OK",@"OK"),nil];
    [alert setTag:0]; //so we know in the callback of the alert where we come from - in case we have multiple different alerts
    [alert show];
}

//the local callback for the alert - this handles the case when we call the alert with delegate nil
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    D_DBG(@"%i %i",[alertView tag],buttonIndex);
}

Import the *.h file in your UIViewController class where you need the alert.

Now if you call like this:

   [self showAlertWithDelegate:nil];

it will show your alert and the delegate will be the implemented

 - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex

IN THE INTERFACE while when you call it like this:

   [self showAlertWithDelegate:self];

You need to provide the callback

 - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex

IN THE CLASS YOU CALLED IT FROM, so you can handle whatever the user pressed - differently from what is implemented in the interface.

链接地址: http://www.djcxy.com/p/20346.html

上一篇: CLLocationManager没有正确更新数据

下一篇: 在哪里放置通用的UIAlertView代码