views:

532

answers:

1

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?

+7  A: 

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) {
        // ...
    }
}
Can Berk Güder
Ah, nice. Though I'd use a switch. :)
quano
of course a switch would work too, but I never liked switch. =)
Can Berk Güder
Great answer. But that leads me to another question. Why do you define the kAlertViewOne 1 and kAlertViewRwo 2. Couldn't you just use in the alertView.tag = 1 or alertView.tag = 2?Is this done for a reason?
George
kAlertViewOne and kAlertViewTwo make more sense than 1 or 2. for example, in your question, you can use kAlertResume and kAlertRetry, and they'd be more readable than two random numbers.
Can Berk Güder
Is there a reason you would not have them strings?
George
tag is defined as an NSInteger.
Can Berk Güder
FYI, assigning tags the numbers less than 10 might conflict with those Apple rarely uses.
Comptrol
Incidentally you can cast a NSString * into a NSInteger and read it back later. However that may be too kludgy for some.
futureelite7