Created
February 8, 2019 15:13
-
-
Save onurhuseyincantay/4c4df58aa5b62705af3acba69e95db5d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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