Search code examples
iosobjective-cdelegatesdryreusability

Reuse identical delegate methods in multiple controllers?


I have a UITextFieldDelegate method shouldChangeCharactersInRange that is exactly the same across several view controllers, so I had to just copy-paste it into every view controller that conforms to the UITextFieldDelegate. I like sticking to DRY, and here I have identical code in lots of view controllers. Is it possible to reuse delegate methods and what are good ways to do it, or this is the only/optimal way and why?


Solution

  • Create a sub class of UIViewController which implements just the delegate methods you wish. Set this as the parent class of all the view controllers in your project which want the delegate methods to be used.

    Instead of that, you can also try looking into Categories. Create a category on UIViewController named whatever you wish. Add the delegate methods you wish to implement to this category. Now, all view controllers in which you #import this category will implement the delegate methods.