UIAlertView with blocks, revisited

One issue with my UIAlertView with blocks class is that it only supports willDismiss, not any other delegate methods supported by UIAlertViewDelegate. At the time I wrote it, that was all I needed, but more recently, my requirements changed. (Hint: if you’re presenting a UIActionSheet from within a willDismiss delegate method call, bad things will probably happen, as of iOS 4.2).

So I’ve updated it to support all the other UIAlertViewDelegate methods. It’s pretty straightforward.

First we make typedefs for each type of block, one corresponding to each UIAlertViewDelegate method.

typedef void (^WillPresentBlock)(void);
typedef void (^DidPresentBlock)(void);
typedef void (^DidCancelBlock)(void);
typedef void (^ClickedButtonBlock)(NSInteger);
typedef void (^WillDismissBlock)(NSInteger);
typedef void (^DidDismissBlock)(NSInteger);

Then we need an instance variable, and a property for each.

@interface ZPAlertView : UIAlertView
{
    WillPresentBlock willPresentBlock;
    DidPresentBlock didPresentBlock;
    DidCancelBlock didCancelBlock;
    ClickedButtonBlock clickedButtonBlock;
    WillDismissBlock willDismissBlock;
    DidDismissBlock didDismissBlock;
}
@property (nonatomic, copy) WillPresentBlock willPresentBlock;
@property (nonatomic, copy) DidPresentBlock didPresentBlock;
@property (nonatomic, copy) DidCancelBlock didCancelBlock;
@property (nonatomic, copy) ClickedButtonBlock clickedButtonBlock;
@property (nonatomic, copy) WillDismissBlock willDismissBlock;
@property (nonatomic, copy) DidDismissBlock didDismissBlock;
@end

Note that the properties are set for copy. Retaining a block doesn’t work as you’d expect; we need to make a copy.

We synthesize our properties. No need for custom stuff here.

@synthesize willPresentBlock;
@synthesize didPresentBlock;
@synthesize didCancelBlock;
@synthesize clickedButtonBlock;
@synthesize willDismissBlock;
@synthesize didDismissBlock;

Since we’ve made our properties copy, we need to make sure we release them in dealloc.

- (void) dealloc
{
    [willPresentBlock release];
    [didPresentBlock release];
    [didCancelBlock release];
    [clickedButtonBlock release];
    [willDismissBlock release];
    [didDismissBlock release];

    [super dealloc];
}

The real magic is in our overridden show method, which doesn’t look very much like magic at all:

- (void) show
{
    self.delegate = self;
    [super show];
}

Finally we have the actual delegate method calls, each of which call the appropriate block. That’s it.

- (void) willPresentAlertView:(UIAlertView*)alertView
{
    if( willPresentBlock != nil ) {
        willPresentBlock();
    }
}

- (void) didPresentAlertView:(UIAlertView*)alertView
{
    if( didPresentBlock != nil ) {
        didPresentBlock();
    }
}

- (void) alertViewCancel:(UIAlertView *)alertView
{
    if( didCancelBlock != nil ) {
        didCancelBlock();
    }
}

- (void) alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if( clickedButtonBlock != nil ) {
        clickedButtonBlock(buttonIndex);
    }
}

- (void) alertView:(UIAlertView*)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if( willDismissBlock != nil ) {
        willDismissBlock(buttonIndex);
    }
}

- (void) alertView:(UIAlertView*)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if( didDismissBlock != nil ) {
        didDismissBlock(buttonIndex);
    }
}

The client code would look like this:

- (void) doLengthyOperationPrompt
{
    enum {
        ButtonIndexCancel = 0,
        ButtonIndexDoItNow,
        ButtonIndexDoItLater
    };

    ZPAlertView* anAlert = [[ZPAlertView alloc] initWithTitle:@"Warning!"
        message:@"Would you like to perform a really lengthy operation?"
        delegate:nil
        cancelButtonTitle:@"Nope"
        otherButtonTitles:@"Yeah, sure", @"Meh, maybe later", nil];
    anAlert.didDismissBlock = ^(NSInteger buttonIndex){
        switch( buttonIndex ) {
            case ButtonIndexDoItNow:
                [self performLengthyOperation];
            break;
            case ButtonIndexDoItLater:
                [self scheduleLengthyOperationForLater];
            break;
        }
    };
    [anAlert show];
    [anAlert release];
}

I’ll try to put the full source and and example project up somewhere, soon. Any and all feedback is welcome.

Update: It’s now up on github, here.

If you want to follow me, I’m @zpasternack on Twitter and on app.net.

UIAlertView with blocks

When extending behavior in Objective-C (unlike in other OO languages), subclassing is not always your first choice. In particular, the Cocoa framework makes extensive use of the Delegation pattern. While this works very well in general, it can at times become cumbersome. Consider a ViewController that wants to display an alert:

//  MyViewController.m
#import “MyViewController.h”

enum {
    ButtonIndexCancel = 0,
    ButtonIndexDoItNow,
    ButtonIndexDoItLater,
    LengthyOperationAlertTag = 100
};

@implementation MyViewController

- (void) doLengthyOperationPrompt
{
    UIAlertView* anAlert = [[UIAlertView alloc] initWithTitle:@"Warning!"
                    message:@"Would you like to perform a lengthy operation?"
                   delegate:self
          cancelButtonTitle:@"Nope"
          otherButtonTitles:@"Yeah, sure", @"Meh, maybe later", nil];
    anAlert.tag = LengthyOperationAlertTag;
    [anAlert show];
    [anAlert release];
}

- (void) alertView:(UIAlertView*)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if( alertView.tag == LengthyOperationTag ) {
        switch( buttonIndex ) {
            case ButtonIndexDoItNow:
                [self performLengthyOperation];
            break;
            case ButtonIndexDoItLater:
                [self scheduleLengthyOperationForLater];
            break;
        }
    }
}
@end

But Zach, I hear you say, what’s wrong with that? And I agree, it’s not too terrible taken on it’s own. Thing is, I’m betting MyViewController does a whole lot of things other than showing an alert. Meaning, the chances are good that your doLengthyOperationPrompt and alertView:willDismissWithButtonIndex: methods are not actually right next to each other. And, they’re probably not at the top either. So you have three related pieces of code (the enums, the code to show the alert, and the code to handle the button press) which are most likely physically segregated from one another. Now imagine MyViewController has a half-dozen different UIAlertViews, each with different buttons and tags and code called in response. It adds up to a whole lotta ugly pretty quickly.

Wouldn’t it be better if all three related pieces of code were in the same place? In my dream, it would look like this:

//  MyViewController.m
#import “MyViewController.h”

@implementation MyViewController

- (void) doLengthyOperationPrompt
{
    enum {
        ButtonIndexCancel = 0,
        ButtonIndexDoItNow,
        ButtonIndexDoItLater
    };

    UIAlertView* anAlert = [[UIAlertView alloc] initWithTitle:@"Warning!"
                    message:@"Would you like to perform a lengthy operation?"
                   delegate:self
          cancelButtonTitle:@"Nope"
          otherButtonTitles:@"Yeah, sure", @"Meh, maybe later", nil];
    [anAlert showWithCompletion:^(NSInteger buttonIndex) {
        switch( buttonIndex ) {
            case ButtonIndexDoItNow:
                [self performLengthyOperation];
            break;
            case ButtonIndexDoItLater:
                [self scheduleLengthyOperationForLater];
            break;
        }
    }];
    [anAlert release];
}
@end

The code that handles the button presses is right there next to the code that displays the alert, preventing you from having to scroll around to follow the flow. In addition, because they’re in the same scope, we don’t have to declare the enum at the top – this is the only function that uses it – so it’s also there in the same place. Nice and compact, and all the related functionality is in close physical proximity. But how do we get there?

As I mentioned before, subclassing isn’t always the first choice as a means to extend functionality. My knee-jerk inclination was to implement this as a class extension to UIAlertView. Unfortunately, extensions can only add member functions, not iVars, making this approach problematic. The easy way, in this case, is to subclass.

It seems simple enough, we’ll need a showWithCompletion: member function into which we pass our block. Our class will need an iVar to hold the block. Then showWithCompletion: can set delegate to itself, and call the block on it’s own alertView:willDismissWithButtonIndex:.

It looks a little somethin’ like this:

//  ZPAlertView.h
#import <Foundation/Foundation.h>

typedef void (^AlertCompletion)(NSInteger);

@interface ZPAlertView : UIAlertView
{
    AlertCompletion completionBlock;
}
- (void) showWithCompletion:(AlertCompletion)aBlock;
@end


//  ZPAlertView.m
#import "ZPAlertView.h"

@implementation ZPAlertView

- (void) showWithCompletion:(AlertCompletion)aBlock
{
    self.delegate = self;
    completionBlock = [aBlock copy];
    [self show];
}

- (void) alertView:(UIAlertView*)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    completionBlock(buttonIndex);
    [completionBlock release]; completionBlock = nil;
}

@end

Stupid simple, right?

We start out by creating a typedef for our block. It takes a single parameter of type NSInteger and has no return value. This isn’t quite the same as alertView:willDismissWithButtonIndex, because we don’t supply the alertView. There’s no need to, because it’s right there in the scope of our block. We add one function, showWithCompletion:, which takes the block which will be executed.

showWithCompletion: sets the delegate to self (because we’ll be handling alertView:willDismissWithButtonIndex: ourselves), stores off a copy of the completion block, and calls [self show]. We take a copy of the block, because the block was created on the stack, and will be going out of scope before we execute it later, so the copy gives a copy on the heap which will stick around until we’re done with it.

The magic happens in alertView:willDismissWithButtonIndex:. We simply call the block, and then release it. That’s it.

Using this class, we can do exactly like I wanted above, by only replacing UIAlertView with ZPAlertView:

//  MyViewController.m
#import “ZPAlertView.h”
#import “MyViewController.h”

@implementation MyViewController

- (void) doLengthyOperationPrompt
{
    enum {
        ButtonIndexCancel = 0,
        ButtonIndexDoItNow,
        ButtonIndexDoItLater
    };

    ZPAlertView *anAlert = [[ZPAlertView alloc] initWithTitle:@"Warning!"
                    message:@"Would you like to perform a lengthy operation?"
                   delegate:self
          cancelButtonTitle:@"Nope"
          otherButtonTitles:@"Yeah, sure", @"Meh, maybe later", nil];
    [anAlert showWithCompletion:^(NSInteger buttonIndex) {
        switch( buttonIndex ) {
            case ButtonIndexDoItNow:
                [self performLengthyOperation];
            break;
            case ButtonIndexDoItLater:
                [self scheduleLengthyOperationForLater];
            break;
        }
    }];
    [anAlert release];
}
@end

You can do lots of cool stuff with this. Want to put a text field on there? No problem!

- (void) doAlertWithTextField
{
    ZPAlertView *alert = [[ZPAlertView alloc] initWithTitle:@"Hello!"
                    message:@"Please enter your name:\n\n\n"
                   delegate:nil
          cancelButtonTitle:nil
          otherButtonTitles:@"OK", nil];
    UITextField *nameEntryField = [[UITextField alloc] initWithFrame:CGRectMake(12, 90, 260, 25)];
    nameEntryField.backgroundColor = [UIColor whiteColor];
    nameEntryField.keyboardType = UIKeyboardTypeAlphabet;
    nameEntryField.keyboardAppearance = UIKeyboardAppearanceAlert;
    nameEntryField.autocorrectionType = UITextAutocorrectionTypeNo;
    nameEntryField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [alert addSubview:nameEntryField];
    [nameEntryField becomeFirstResponder];
    [nameEntryField release];
    [alert showWithCompletion:^(NSInteger buttonIndex) {
        UIAlertView *anAlert = [[UIAlertView alloc] initWithTitle:@"Greetings!"
                        message:[NSString stringWithFormat:@"Hello, %@", nameEntryField.text]
                       delegate:nil
              cancelButtonTitle:nil
              otherButtonTitles:@"OK", nil];
        [anAlert show];
        [anAlert release];
    }];
    [alert release];
}

Normally when you do such a thing (as I’ve written about before), you need to set a tag on the UITextField so you can find it later in alertView:willDismissWithButtonIndex to get at the text. This way, there’s no need for that, because it’s still in the scope of our block.

One limitation of this is that UIAlertViewDelegate has a bunch of delegate methods aside from alertView:willDismissWithButtonIndex:. If you wanted to do something in other delegate methods, you’d need to modify it to do that. For my purposes, all I needed was willDismissWithButtonIndex. Also, showWithCompletion: is replacing whatever delegate you specified in your initWithTitle:message:delegate:cancelButtonTitle:otherButtonTitles: call, so you can’t really use any of the other delegate methods (of course, you could just call show if you wanted to do that, or just use a regular UIAlertView).

One could probably implement this as a class extension, but there are issues with doing so. For one thing, you can’t add any iVars to a class extension, only member functions. You could get around this by, say, storing a static dictionary mapping UIAlertViews to AlertCompletion blocks. But that is kinda icky. Plus, the semantics of an NSDictionary are to copy the key, so you couldn’t use the UIAlertView as the key, unless you take the integer value of the pointer and wrap that in a NSNumber. Double icky. That’s about as far along as I’ve gotten in the process of making this into a class extension, but if someone has a better idea, I’d love to hear it.

Note that I haven’t used this in any production code yet – PuzzleTiles 1.1 is close enough to release that I’m disinclined to make such seemingly gratuitous changes – so I don’t know if there are any gotchas I haven’t thought of. Use it at your own risk, I’m saying. If you do find use for it, or have ideas for how to improve it, let me know!

Update: The above paragraph is no longer true; I’m using this code (actually, an updated version of this code) in both PuzzleTiles and PuzzleTiles HD.

If you want to follow me, I’m @zpasternack on Twitter and on app.net.