views:

218

answers:

2

I'm sick of writing basic UIAlertView's, ie:

UIAlertView *alert = [[UIAlertView alloc] initWith...]] //etc

Instead of doing this, is it possible to put all this in a "helper" function, where I can return the buttonIndex, or whatever an alert usually returns?

For a simple helper function I guess you could feed parameters for the title, message, I'm not sure whether you can pass delegates in a parameter though, or bundle info.

In pseudo-code, it could be like this:

someValueOrObject = Print_Alert(Title="", Message="", Delegate="", Bundle="") // etc

Any help on this would be great.

Thanks

A: 

This is what I wrote, when I got sick of doing the same:

-(void)alert:(NSString *)title withBody:(NSString *)message firstButtonNamed:(NSString *)firstButtonName {
  [self alert: title withBody: message firstButtonNamed: firstButtonName withExtraButtons: nil informing: nil];
}

-(void)alert:(NSString *)title withBody:(NSString *)message firstButtonNamed:(NSString *)firstButtonName informing:(id)delegate {
  [self alert: title withBody: message firstButtonNamed: firstButtonName withExtraButtons: nil informing: delegate];
}

-(void)alert:(NSString *)title withBody:(NSString *)message firstButtonNamed:(NSString *)firstButtonName withExtraButtons:(NSArray *)otherButtonTitles informing:(id)delegate {
  UIAlertView *alert = [[UIAlertView alloc]
              initWithTitle: title
              message: message
              delegate: delegate
              cancelButtonTitle: firstButtonName
              otherButtonTitles: nil];
  if (otherButtonTitles != nil) {  
    for (int i = 0; i < [otherButtonTitles count]; i++) {
      [alert addButtonWithTitle: (NSString *)[otherButtonTitles objectAtIndex: i]];
    }
  }
  [alert show];
  [alert release];
}

You can't write a function that will display an alert and then return a value like a buttonIndex though, because that value-returning only occurs when the user presses a button and your delegate does something.

In other words, the process of asking a question with the UIAlertView is an asynchronous one.

Frank Shearar
Oh, okay. Thanks for your help!
zardon
+2  A: 

In 4.0 you can simplify the alert code using blocks, a bit like this:

LambdaAlert *alert = [[LambdaAlert alloc]
    initWithTitle:@"Test Alert"
    message:@"See if the thing works."];
[alert addButtonWithTitle:@"Foo" block:^{ NSLog(@"User pressed Foo"); }];
[alert addButtonWithTitle:@"Bar" block:^{ NSLog(@"User pressed Bar"); }];
[alert setCancelButtonWithTitle:@"Cancel" block:NULL];
[alert show];
[alert release];

See Lambda Alert on GitHub.

zoul