Skip to content
Browse files

Use objc runtime libs to copy the blocks (avoiding static blocks).

  • Loading branch information...
1 parent 7ff9e1f commit a283e213a58a461a05bbd640e246a27547bbbc27 @hwaxxer hwaxxer committed May 25, 2012
Showing with 40 additions and 11 deletions.
  1. +3 −0 MKAdditions/UIAlertView+MKBlockAdditions.h
  2. +37 −11 MKAdditions/UIAlertView+MKBlockAdditions.m
View
3 MKAdditions/UIAlertView+MKBlockAdditions.h
@@ -24,4 +24,7 @@
onDismiss:(DismissBlock) dismissed
onCancel:(CancelBlock) cancelled;
+@property (nonatomic, copy) DismissBlock dismissBlock;
+@property (nonatomic, copy) CancelBlock cancelBlock;
+
@end
View
48 MKAdditions/UIAlertView+MKBlockAdditions.m
@@ -7,31 +7,53 @@
//
#import "UIAlertView+MKBlockAdditions.h"
+#import <objc/runtime.h>
-static DismissBlock _dismissBlock;
-static CancelBlock _cancelBlock;
+static char DISMISS_IDENTIFER;
+static char CANCEL_IDENTIFER;
@implementation UIAlertView (Block)
+@dynamic cancelBlock;
+@dynamic dismissBlock;
+
+- (void)setDismissBlock:(DismissBlock)dismissBlock
+{
+ objc_setAssociatedObject(self, &DISMISS_IDENTIFER, dismissBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
+}
+
+- (DismissBlock)dismissBlock
+{
+ return objc_getAssociatedObject(self, &DISMISS_IDENTIFER);
+}
+
+- (void)setCancelBlock:(CancelBlock)cancelBlock
+{
+ objc_setAssociatedObject(self, &CANCEL_IDENTIFER, cancelBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
+}
+
+- (CancelBlock)cancelBlock
+{
+ return objc_getAssociatedObject(self, &CANCEL_IDENTIFER);
+}
+
+
+ (UIAlertView*) alertViewWithTitle:(NSString*) title
message:(NSString*) message
cancelButtonTitle:(NSString*) cancelButtonTitle
otherButtonTitles:(NSArray*) otherButtons
onDismiss:(DismissBlock) dismissed
onCancel:(CancelBlock) cancelled {
-
- [_cancelBlock release];
- _cancelBlock = [cancelled copy];
-
- [_dismissBlock release];
- _dismissBlock = [dismissed copy];
-
+
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:[self class]
cancelButtonTitle:cancelButtonTitle
otherButtonTitles:nil];
+ [alert setDismissBlock:dismissed];
+ [alert setCancelBlock:cancelled];
+
for(NSString *buttonTitle in otherButtons)
[alert addButtonWithTitle:buttonTitle];
@@ -64,11 +86,15 @@ + (void)alertView:(UIAlertView*) alertView didDismissWithButtonIndex:(NSInteger)
if(buttonIndex == [alertView cancelButtonIndex])
{
- _cancelBlock();
+ if (alertView.cancelBlock) {
+ alertView.cancelBlock();
+ }
}
else
{
- _dismissBlock(buttonIndex - 1); // cancel button is button 0
+ if (alertView.dismissBlock) {
+ alertView.dismissBlock(buttonIndex - 1); // cancel button is button 0
+ }
}
}

0 comments on commit a283e21

Please sign in to comment.
Something went wrong with that request. Please try again.