Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Several UIAlertViews for a delegate

Currently I've got a class popping up UIAlertViews here and there. Currently, the same class is the delegate for these (it's very logical that it would be). Unfortunately, these UIAlertViews will call the same delegate methods of the class. Now, the question is - how do you know from which alert view a delegate method is invoked? I was thinking of just checking the title of the alert view, but that isn't so elegant. What's the most elegant way to handle several UIAlertViews?

like image 749
quano Avatar asked Feb 26 '10 00:02

quano


4 Answers

Tag the UIAlertViews like this:

#define kAlertViewOne 1
#define kAlertViewTwo 2

UIAlertView *alertView1 = [[UIAlertView alloc] init...
alertView1.tag = kAlertViewOne;

UIAlertView *alertView2 = [[UIAlertView alloc] init...
alertView2.tag = kAlertViewTwo;

and then differentiate between them in the delegate methods using these tags:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if(alertView.tag == kAlertViewOne) {
        // ...
    } else if(alertView.tag == kAlertViewTwo) {
        // ...
    }
}
like image 162
Can Berk Güder Avatar answered Nov 20 '22 18:11

Can Berk Güder


FYI, if you want to target just iOS 4 users (which is reasonable now that ~98.5% of clients have at least iOS 4 installed), you should be able to use Blocks to do really nice inline handling of UIAlertViews.

Here's a Stackoverflow question explaining it:
Block for UIAlertViewDelegate

I tried using Zachary Waldowski's BlocksKit framework for this. His UIAlertView(BlocksKit) API reference looked really good. However, I tried to follow his instructions to import the BlocksKit framework into my project, but unfortunately I couldn't get it to work.

So, as Can Berk Güder suggests, I've used UIAlertView tags for now. But at some point in future I'm going to try to move to using Blocks (preferably one which supports ARC out of the box)!

like image 39
Dan J Avatar answered Nov 20 '22 20:11

Dan J


easier & newer

UIAlertView *alert = [[UIAlertView alloc] init...
alert.tag = 1;

UIAlertView *alert = [[UIAlertView alloc] init...
alert.tag = 2;



- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if(alertView.tag == 1) {
        // first alert...
    } else  {
        // sec alert...
    }
}

all done!

like image 3
nima sp Avatar answered Nov 20 '22 20:11

nima sp


You can overcome this whole ordeal and prevent yourself from using tags by enhancing UIAlertView to use block callbacks. Check out this blog post I wrote on the subject.

like image 1
Stavash Avatar answered Nov 20 '22 20:11

Stavash