Cocoa uses delegates extensively to provide (among other things) callback methods for asynchronous operations. However, I personally hate the delegate model and how it pollutes the current class with handlers for very specific child operations. UIAlertView
is a perfect example.
Therefore, I'm wondering if it's possible to simply create an anonymous delegate object that meets the requirements of a delegate protocol (such as UIAlertViewDelegate
) via blocks and pass this anonymous object wherever a delegate reference is expected.
I imagine something like so:
id myDelegate = @{
alertView:alertView didDismissWithButtonIndex:index = ^ {
...
}
};
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:... message:... delegate:myDelegate cancelButtonTitle:... otherButtonTitles:...;
[alertView show];
I've heard Objective-C has some good dynamic language features but I don't know how to simply add a method/selector to an object. Can this be done in a relatively straightforward manner?