Sunday, November 6, 2011

UIAlert with Blocks

I wish Apple would make a version of UIAlert with blocks.  I have seen a fair number of simple examples on how to do this, but I have been unhappy with most of them.  Most use Categories on UIAlert, and I would rather not do that especially when the alert handler is also involved.

This very simple implementation uses a separate class to implement a UIAlert.  Here is how you use it:
    
TCAlert *alert = [[TCAlert alloc] initWithTitle:@"Reset Puzzles" 
                                        message:@"Reset ALL puzzles in this puzzle pack?"
                              cancelButtonTitle:@"Cancel" 
                              otherButtonTitles:@"Yes", nil];
   
[alert showAlertWithCompletionBlock:^(int buttonIndex)
                                    {
                                        NSLog( @"Hello I got it %d", buttonIndex );
                                        [alert release];
                                    }];
It is important that the alert object stay retained through the life of the Alert, but that is easy to do by releasing it in the block.  The block will retain the alert!  If the system closes the alert the completion block will be called with a buttonIndex of -1 (kAlertViewCanceled).

The code is just a small source and header file.  Please feel free to download it and let me know what you think.  I haven't switched over to ARC yet, so I'm not sure what would need to be changed to support ARC.  It would be great if someone would like to do that.

Thanks,
- Tod





No comments:

Post a Comment