Skip to content

Instantly share code, notes, and snippets.

@rzolin
Last active December 27, 2015 11:29
Show Gist options
  • Save rzolin/7318940 to your computer and use it in GitHub Desktop.
Save rzolin/7318940 to your computer and use it in GitHub Desktop.
Showing UIAlertView when controller is being closed, and based on the answer (e.g. Yes/No) perform some action in the controller. The controller is not dismissed till the UIAlertView is handled (clicked). This is very simple and clean code without adding complexity of protocols and delegates, but using objc_setAssociatedObject method.
#import <objc/runtime.h>
// A key to bind UIAlertView and the controller (could be any unchangeable void*)
static const char * const kAlertAssociationKey = "alertKey";
// Action to close the ViewController
- (IBAction) handleCancelTap
{
WCAlertView *alert = [[WCAlertView alloc] initWithTitle:@"Unsaved Data" message:@"Would you like to save the data to edit or submit later?" delegate:self cancelButtonTitle:@"NO" otherButtonTitles:@"YES", nil];
[alert show];
// Prevent the controller to be deallocated before the alert is processed (released)
objc_setAssociatedObject(alert, kAlertAssociationKey, self, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - UIAlertVieDelegate
- (void) alertView:(UIAlertView *) alertView clickedButtonAtIndex:(NSInteger) buttonIndex
{
// Safely do your actions here
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment