Debugging the Responder Chain in Swift

By · Published · swift, macos, ios

Somewhat related to my previous post about responder chains, sometimes it is useful to be able to debug what all is in the responder chain at any given time. As a good rule of thumb, all ancestor views of a view are in that view's responder chain, as well as (usually) the related controllers.

But this information is not always clear, so here's a little class that will print the entire responder chain for any given object, starting with the current object and proceeding up the chain until it reaches the end.

class DebugHelper {
    static func printResponderChain(from responder: NSResponder?) {
        var responder = responder
        while let r = responder {
            print(r)
            responder = r.nextResponder
        }
    }
}

This is for macOS. For iOS, just change NSResponder to UIResponder.

You can call it like this from a view controller:

override func viewDidAppear() {
    DebugHelper.printResponderChain(from: self)
}

And it will output something like this:

<Example.FilesViewController: 0x600003500b00>
<_NSSplitViewItemViewWrapper: 0x600003b01340>
<NSSplitView: 0x6000033010e0>
<NSView: 0x6000033012c0>
<Example.MainSplitViewController: 0x600002c07900>
<NSView: 0x600003301040>
<NSView: 0x600003300fa0>
<Example.ViewController: 0x60000350c000>
<NSWindow: 0x600003e08200>
<Example.MainWindowController: 0x6000033108c0>

The above example was taken from a subclass of NSViewController. As you can see, there is more in the responder chain than you might have guessed. In addition to the view controllers, all the views as well as the windows and window controllers are also in the responder chain.

( Comments )

Did something I wrote help you out?

That's great! I don't earn any money from this site - I run no ads, sell no products and participate in no affiliate programs. I do this solely because it's fun; I enjoy writing and sharing what I learn.

All the same, if you found this article helpful and want to show your appreciation, here's my Amazon.com wishlist.


Related Posts

Hierarchies: Finding Parents, Children and Descendents using Swift

Creating Traits or Mixins in Swift


comments powered by Disqus