Created
December 5, 2014 16:34
-
-
Save darren102/f4f6eaaa92b0bd9be921 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
----------- .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