Skip to content

Instantly share code, notes, and snippets.

@neiraza
Created September 6, 2013 04:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neiraza/6459400 to your computer and use it in GitHub Desktop.
Save neiraza/6459400 to your computer and use it in GitHub Desktop.
UIAlertViewでdelegateをダラダラ書くのは嫌だ
#import <UIKit/UIKit.h>
@interface UIAlertView (UIAlertView_BlocksExtension)
typedef void (^UIAlertViewCallback_t)(NSInteger buttonIndex);
- (id)initWithTitle:(NSString *)title
message:(NSString *)message
callback:(UIAlertViewCallback_t)callback
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitles, ...;
@end
#import "UIAlertView+UIAlertView_BlocksExtension.h"
#import "UIAlertViewCallback.h"
@implementation UIAlertView (UIAlertView_BlocksExtension)
- (id)initWithTitle:(NSString *)title message:(NSString *)message callback:(UIAlertViewCallback_t)callback cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ...
{
self = [self initWithTitle:title message:message delegate:nil cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil];
if (self) {
va_list args;
va_start(args, otherButtonTitles);
for (NSString *arg = otherButtonTitles; arg != nil; arg = va_arg(args, NSString*)) {
[self addButtonWithTitle:arg];
}
va_end(args);
self.delegate = [[[UIAlertViewCallback alloc] initWithCallback:callback] autorelease];
}
return self;
}
@end
#import <Foundation/Foundation.h>
#import "UIAlertView+UIAlertView_BlocksExtension.h"
@interface UIAlertViewCallback : NSObject<UIAlertViewDelegate>
{
UIAlertViewCallback_t callback;
}
@property (nonatomic, copy) UIAlertViewCallback_t callback;
- (id)initWithCallback:(UIAlertViewCallback_t) callback;
@end
#import "UIAlertViewCallback.h"
@implementation UIAlertViewCallback
@synthesize callback;
- (id)initWithCallback:(UIAlertViewCallback_t)aCallback
{
if(self = [super init]) {
self.callback = aCallback;
[self retain];
}
return self;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (callback) {
callback(buttonIndex);
}
[self release];
}
- (void)dealloc
{
self.callback = nil;
[super dealloc];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment