Skip to content

Instantly share code, notes, and snippets.

@matej
Created November 7, 2012 13:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matej/4031676 to your computer and use it in GitHub Desktop.
Save matej/4031676 to your computer and use it in GitHub Desktop.
UIAlertView with blocks support
//
// 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
//
// 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