How to create UIAlertView with blocks in ~20 lines of code
In my current project I had to change flow of "success and error blocks" in API calls, and add "retry block" in order to be able to retry every failed connection. It turned out to be not so trivial task in current architecture, but I've managed to do it with using alert views with blocks (it's not so interesting how at the moment). At first I've used some libraryĀ that supported blocks, but also changed completely alert view pattern
http://i.imgur.com/3s3eJ.png
We did like it, but client decided it's too different from default, so I needed to changed it. At first I've looked for solutions with default Alert View, but didn't find anything good enough. So I've decided to create my own UIAlertView category that supports block in about 20 lines of code:
#import <UIKit/UIKit.h> typedef void(^UIAlertViewActionBlock)(void); @interface UIAlertView (Blocks) - (void)addBlock:(UIAlertViewActionBlock)block; - (void)addBlock:(UIAlertViewActionBlock)block forButtonIndex:(NSInteger)index; @end
#import "UIAlertView+Blocks.h" #import <objc/runtime.h> @implementation UIAlertView (Blocks) static NSString *handlersDictionaryKey = @"handlersDictionaryKey"; - (void)addBlock:(UIAlertViewActionBlock)block { [self addBlock:block forButtonIndex:self.firstOtherButtonIndex]; } - (void)addBlock:(UIAlertViewActionBlock)block forButtonIndex:(NSInteger)index { NSMutableDictionary *handlersDictionary = objc_getAssociatedObject(self, (__bridge void *)handlersDictionaryKey); if (handlersDictionary == nil) { handlersDictionary = [NSMutableDictionary dictionary]; } handlersDictionary[@(index)] = block; objc_setAssociatedObject(self, (__bridge void *)handlersDictionaryKey, handlersDictionary, OBJC_ASSOCIATION_RETAIN_NONATOMIC); self.delegate = self; } #pragma mark - UIAlertViewDelegate - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { NSMutableDictionary *handlersDictionary = objc_getAssociatedObject(self, (__bridge void *)handlersDictionaryKey); if (handlersDictionary) { UIAlertViewActionBlock handler = handlersDictionary[@(buttonIndex)]; if (handler) { handler(); } } } @end
And thath's it. Now you have your block in UIAlertView

















