Sometimes, the delegate pattern in iOS just doesn’t fit with a class heirarchy or design, specifically when you find yourself wanting to assign multiple delegates to a single source. For these cases, the approach usually taken is to use the notification center. This is an approach I have used in the past, but it always felt like a cop-out. Instead, I decided to build a delegate proxy using an NSProxy subclass. It takes a list of target delegates, and operates on two simple rules:
- Messages with a void return type are sent to all target delegates
- Messages with non-void return types are send to the first delegate in the list which responds to the selector.
This pattern seems to be effective in identifying which messages are informative (hey, something happened) and which messages are more complex interactions (how should I do this?). It worked well for my use case (UIScrollViewDelegate), and I’m really curious to see how well it works for other applications. Comment if you find some use for it! Podspec included for CocoaPods users.
The class HTDelegateProxy is available on GitHub.