Hiding selector methods

On the Tumblr iOS team, we have a strict rule that everything with an internal or public visibility must be documented1. This gets a bit awkward when using the Target-Action pattern that UIKit often forces you into. When dealing with multiple action selectors, it makes sense to factor out the target into a separate object. However, we’ll often just need a one-off action selector to handle an event from a UIControl subclass. Previously, this would lead to the following scenario and awkward comment:

I was curious if we could make SampleViewController.buttonTapped(_:) private, thus avoiding the need to specify that the method shouldn’t be called externally, in its documentation. My teammate Paul pointed out that this is actually possible! To do this, we simply have to expose the method to the Objective-C runtime and give it a private access modifier:

This allows our action to be invoked from a selector, but prevents other files from accessing the method directly 🎉 Hope this helps better encapsulate your types!


Footnotes:

  1. To help with this, we use VVDocumenter