Objective-C: Subclassing for delegate behavior

May 10th, 2014 0 comments

Have you ever wanted to re-use a delegate implementation? Maybe, the fix for the UITextView return bug? Turns out, with some help from the Objective-C runtime, you totally can! That said, this is definitely a hack.

First, we’ll subclass UITextView. Then, we set ourself as super’s delegate and and create a private externalDelegate property, so that we can keep a second delegate. Then, we implement the return bug fix in textView:shouldChangeTextInRange:replacementText:, calling externalDelegate’s implementation (if it exists).

“But Phil,” you say, “What about all of the other delegate methods? How could our external delegate receive those as well?”

We’ll use the NSObject method forwardingTargetForSelector: to forward methods, and we’ll use the runtime’s protocol_getMethodDescription to tell us if a selector is in UITextViewDelegate or not. Basically, we put them together, and it scales right up!

Code for this fix is here.

Leave a Reply

Your email address will not be published. Required fields are marked *