I suggest that you use a subclass of UIAlertView
that is able to track some more properties along. I do this in all my projects and it is much simpler.
- One solution to do this would be to subclass
UIAlertView
to MyAlertView
and add a @property(nonatomic, retain) id userInfo;
or @property(nonatomic, retain) NSURL* urlToOpen
. Thus you can attach custom data to your UIAlertView
and retrieve it in the delegate method to do whatever you need with it.
- Another solution, and my preferred one actually, is to add Objective-C blocks support to
UIAlertView
, to be able to use UIAlertView
using the blocks API instead of using a delegate
. This is particularly useful if you use multiple UIAlertViews
in the same class and with the same delegate, as using a single delegate to handle the different instances is a mess.
I personally use this technique all the time, as it also makes my code more readable by having the code that executes when the button is tapped right next to the code that shows the alert, instead of having it at a complete different places when you use delegate methods.
You can look at my OHAlertView
subclass here on GitHub that implement this already. The usage is really simple and allow you to use blocks for each alert view instead of a common delegate, see below.
Usage Example
-(void)confirmOpenURL:(NSURL*)url
{
NSString* message = [NSString string WithFormat:@"Open %@ in Safari?",
url.absoluteString];
[OHAlertView showAlertWithTitle:@"Open URL"
message:message
cancelButton:@"No"
okButton:@"Yes"
onButtonTapped:^(OHAlertView* alert, NSInteger buttonIndex)
{
if (buttonIndex != alert.cancelButtonIndex)
{
// If user tapped "Yes" and not "No"
[[UIApplication sharedApplication] openURL:url];
}
}];
}
Then each button can have its own action:
-(IBAction)button1Action
{
[self confirmOpenURL:[NSURL URLWithString:@"http://www.google.com"]];
}
-(IBAction)button2Action
{
[self confirmOpenURL:[NSURL URLWithString:@"http://www.stackoverflow.com"]];
}
Or you can have a common IBAction for all your buttons opening URLs:
-(IBAction)commonButtonAction:(UIButton*)sender
{
NSUInteger tag = sender.tag;
NSString* urls[] = { @"http://www.google.com", @"http://www.stackoverflow.com" };
NSURL* buttonURL = [NSURL URLWithString: urls[tag] ]; // in practice you should check that tag is between 0 and the number of urls to be sure, that's just an example here
[self confirmOpenURL:buttonURL];
}