Apple: UIAlertView Needs An API Update
Last summer at No Fluff Just Stuff I attended a couple of awesome sessions on functional programming. One aspect of this programming paradigm includes what are called anonymous methods. Like the use of anonymous classes in Java, anonymous methods allow behavior to be defined and passed inline as arguments to other functions. This can be very powerful and causes a programmer to think more in terms with behavior, than necessarily state.
While I really like the delegate pattern of programming that permeates Objective-C, it does add a bit of overhead and can cause a lot of code to have to be written. This is especially true when you talk in terms of UIAlertView
. It is very possible that a class makes heavy use of UIAlertView
to notify a user of of change, double check destructive behavior etc. With this approach you have two alternatives: 1) Have the using class implement the delegate methods of UIAlertView
, or 2) Have to allocate other delegate objects to handle the behavior. Both involve a hefty amount of code, but more than that, there has always been something that rubs me wrong about the fragile relationship between the order of the buttons you pass in and checking the button index to figure out which one was pressed. In that regard, your button order becomes very brittle with change.
After starting to understand Objective-C's implementation of anonymous functions (called 'blocks'), it became very clear that using them with in conjunction with the UIAlertView
would be very powerful. A cursory search on the Internet revealed that someone did just this, creating a clever category for UIAlertView
that would enable it to behave this way. Now, implementing basic behavior with a UIAlertView
became that much easier, cleaner, and non-fragile. Consider the following example:
RIAlertViewButtonItem *cancelItem = [RIAlertViewButtonItem item];
cancelItem.label = @"Cancel";
cancelItem.action = ^{
NSLog(@"Pressed: %@", cancelItem.label);
};
RIAlertViewButtonItem *okItem = [RIAlertViewButtonItem item];
okItem.label = @"OK";
okItem.action = ^{
NSLog(@"Pressed: %@", okItem.label);
};
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"HEY!"
message:@"Blocks and UIAlertView were meant for each other!"
cancelButtonItem:cancelItem
otherButtonItems:okItem, nil];
[alert show];
[alert release];
No delegates, no extraneous code, just the necessary behavior to be implemented due to interaction with the user. Pretty simple. Apple: UIAlertView
needs an API update. And something like this is it.