How do you pass a variable to the UIAlertView delegate?

wusher picture wusher · Apr 30, 2012 · Viewed 17.9k times · Source

How do you pass a variable to the UIAlertView delegate?

I have a variable that I want to use in the alert view delegate. It is only used in the function that shows the UIAlertView and the UIAlertView delegate, so i don't think it should be a property on the controller. Is there a way to attach the variable to UIAlertView and retrieve it in the delegate?

- (void) someUserCondition:(SOCode *)userCode {
    if ([userCode warrentsConfirmation] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Are you sure?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK",nil];        
        [alert setAlertViewStyle:UIAlertViewStyleDefault];  
        //TODO somehow store the code variable on the alert view
        [alert show];
    }
}

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex   {
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
    if ([title isEqualToString:@"OK"]){
       SOCode *userCode = //TODO somehow get the code from the alert view
       [self continueWithCode:code];
    }                                 
}

Answer

warpedspeed picture warpedspeed · Apr 30, 2012

in .h before interface:

extern const char MyConstantKey;
@interface ViewController...

in .m import:

import <objc/runtime.h>

in .m before implementation

const char MyConstantKey;

in .m implementation

-(void)viewDidAppear:(BOOL)animated{ //or wherever

    NSString *aString = @"This is a string";

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Testing" message:@"test is test" delegate:self cancelButtonTitle:@"Okay" otherButtonTitles:nil];

    [alert show];

    [alert release];

    objc_setAssociatedObject(alert, &MyConstantKey, aString, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

 }

in .m alertview callback

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

     NSString *associatedString = objc_getAssociatedObject(alertView, &MyConstantKey);

     NSLog(@"associated string: %@", associatedString);

}