Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
- (void)askUserAQuestion{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle : @"Question Time"
message : @"What do you want to do ?"
delegate : self
cancelButtonTitle : @"Cancel"
otherButtonTitle : @"Continue",
nil];
[alert show];
}
// UIAlertViewDelegate protocol method
- (void)alertView(UIAlertView *)alertView
clickedButtonIndex: (NSInteger)buttonIndex{
if (buttonIndex == 0){
[self doCancel];
}else{
[self doContinue];
}
}
/* what is the problem here the problem is what if we have more than one alert do we have to
write each condition and make code copy-paste
thats wrong in this case we can make an associated object like below
*/
static void *myAlertViewKey = @"myAlertViewKey";
- (void)askUserAQuestion{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle : @"Question Time"
message : @"What do you want to do ?"
delegate : self
cancelButtonTitle : @"Cancel"
otherButtonTitle : @"Continue",
nil];
void (^block)(NSInteger) = ^(NSInteger buttonIndex){
if (buttonIndex == 0){
[self doCancel];
}else{
[self doContinue];
}
}
objc_setAssociatedObject(alert,myAlertViewKey,block,OBJC_ASSOCIATION_COPY);
[alert show];
}
// UIAlertViewDelegate protocol method with associated object method
- (void)alertView(UIAlertView *)alertView
clickedButtonIndex: (NSInteger)buttonIndex{
void (^block)(NSInteger) = objc_getAssociatedObject(alertView,myAlertViewKey);
block(buttonIndex);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.