How do you pass a variable to the UIAlertView delegate?

前端 未结 6 1299
刺人心
刺人心 2020-12-28 16:22

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 functio

6条回答
  •  时光说笑
    2020-12-28 17:15

    in .h before interface:

    extern const char MyConstantKey;
    @interface ViewController...
    

    in .m import:

    import 
    

    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);
    
    }
    

提交回复
热议问题