Skip to content

Instantly share code, notes, and snippets.

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 darren102/f4f6eaaa92b0bd9be921 to your computer and use it in GitHub Desktop.
Save darren102/f4f6eaaa92b0bd9be921 to your computer and use it in GitHub Desktop.
----------- .h file ------------------------------------------------
static void *MCDAlertViewCodeBlockKey = &MCDAlertViewCodeBlockKey;
@interface UIViewController (MCDAlertViewDelegate) <UIAlertViewDelegate>
@end
---------- .m file -------------------------------------------------
#import <objc/runtime.h>
@implementation UIViewController (MCDAlertViewDelegate)
# pragma mark - UIAlertViewDelegate instance methods (UIALERTVIEWDELEGATE)
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
void (^block)(NSInteger) = objc_getAssociatedObject(alertView, MCDAlertViewCodeBlockKey);
// 'block' is always NULL so the delegate is called by the 'alertView' does not have the block of code any longer
if (block) {
block(buttonIndex);
}
}
@end
-------- Some UIViewController .m file -----------------------------------------------------
#import "UIViewController+MCDAlertViewDelegate"
- (void)showAlert
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:NSLocalizedString(@"Report Data Loss", nil)
message:NSLocalizedString(@"You will lose all report data. Are you sure?", nil)
delegate:self
cancelButtonTitle:NSLocalizedString(@"No", nil)
otherButtonTitles:NSLocalizedString(@"Yes", nil),
nil];
objc_setAssociatedObject(alert, MCDAlertViewCodeBlockKey, ^(NSInteger buttonIndex) {
if (buttonIndex == 1) {
// Do something since they clicked "YES" button
// Never getting into this portion of the code
}
}, OBJC_ASSOCIATION_COPY);
[alert show];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment