Created
November 7, 2012 13:49
-
-
Save matej/4031676 to your computer and use it in GitHub Desktop.
UIAlertView with blocks support
This file contains hidden or 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
// | |
// UIAlertView+Blocks.h | |
// | |
// Created by Matej Bukovinski on 19.7.11. | |
// Copyright 2011 Guerrilla Code. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
@interface UIAlertView (Blocks) <UIAlertViewDelegate> | |
- (id)initWithTitle:(NSString *)title message:(NSString *)message; | |
#if NS_BLOCKS_AVAILABLE | |
- (void)addButtonWithTitle:(NSString *)title action:(dispatch_block_t)block; | |
- (void)addCancelButtonWithTitle:(NSString *)title action:(dispatch_block_t)block; | |
#endif | |
@end |
This file contains hidden or 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
// | |
// UIAlertView+Blocks.m | |
// | |
// Created by Matej Bukovinski on 19.7.11. | |
// Copyright 2011 Guerrilla Code. All rights reserved. | |
// | |
#import "UIAlertView+Blocks.h" | |
#import <objc/runtime.h> | |
@implementation UIAlertView (Blocks) | |
#pragma mark - Accessors | |
- (NSMutableArray *)callbacks { | |
static char kCallbacksKey; | |
NSMutableArray *callbacks = (NSMutableArray *)objc_getAssociatedObject(self, &kCallbacksKey); | |
if (!callbacks) { | |
callbacks = [NSMutableArray array]; | |
objc_setAssociatedObject(self, &kCallbacksKey, callbacks, OBJC_ASSOCIATION_RETAIN); | |
} | |
return callbacks; | |
} | |
#pragma mark - Lifecycle | |
- (id)initWithTitle:(NSString *)title message:(NSString *)message { | |
return [self initWithTitle:title message:message delegate:self cancelButtonTitle:nil otherButtonTitles:nil]; | |
} | |
#if NS_BLOCKS_AVAILABLE | |
#pragma mark - Buttons | |
- (void)addButtonWithTitle:(NSString *)title action:(dispatch_block_t)block { | |
[self addButtonWithTitle:title]; | |
if (!block) block = ^{}; | |
[[self callbacks] addObject:[block copy]]; | |
} | |
- (void)addCancelButtonWithTitle:(NSString *)title action:(dispatch_block_t)block { | |
[self setCancelButtonIndex:[self callbacks].count]; | |
[self addButtonWithTitle:title action:block]; | |
} | |
#pragma mark - UIAlertViewDelegate | |
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { | |
dispatch_block_t callback = [[self callbacks] objectAtIndex:buttonIndex]; | |
if (callback) { | |
callback(); | |
} | |
} | |
#endif | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment