Say you’re working on an iOS view controller that presents UIAlertViews in numerous locations. Implementing button actions soon becomes a nightmare as you have to identify and handle each UIAlertView case-by-case in delegate methods such as -alertView:didDismissWithButtonIndex:.
Fortunately, we can simplify this and reduce boilerplate code with a nifty category on UIAlertView that introduces a Block-based method of presenting alerts:
With this API, we can present alerts and handle their buttons’ actions inline.
Under the hood, we assign the UIAlertView’s delegate object to itself and take advantage of the Associated Objects API to associate the button handler block with the alert view (Blocks are first-class Objective-C objects). When a button is tapped and the alert view’s delegate method fires, we invoke the cached button handler block.