Skip to content

Instantly share code, notes, and snippets.

@onurhuseyincantay
Created February 8, 2019 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onurhuseyincantay/4c4df58aa5b62705af3acba69e95db5d to your computer and use it in GitHub Desktop.
Save onurhuseyincantay/4c4df58aa5b62705af3acba69e95db5d to your computer and use it in GitHub Desktop.
- (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