Posts Tagged ‘ResponderChain’

NSViewController, the New C in MVC - Pt. 2 of 3

Thursday, April 17th, 2008

In the last post on NSViewController, I described the need for a view controller class that is part of a sound controller architecture, especially when developing an application with a single window interface. In this post, Jonathan Dann and I will share the design we came up with for integrating NSViewController into the existing Cocoa MVC application architecture using NSWindowController as the glue.

Before, we do that…

Meet Jonathan.

I’m currently training with the National Health Service in the UK, working towards becoming a state-registered Medical Physicist. I was introduced to programming during my Bachelor’s degree where I did a short course in C. During my Master’s degree I learnt some FORTRAN and then had my first experience of object-oriented programming during that year. Since then I’ve been learning as much as I could about Cocoa, design patterns, and the whole world of Mac programming. I’ve begun to write my first app, which will be available sometime around September, which really began life as a personal project when the tool I was using didn’t work right and didn’t fit properly within OS X.

As my code grew in size I soon realised that I needed a controller for some of my more complex view behaviour, NSSplitViews, NSTextViews, NSOutlineViews all need delegates to unlock their power and when all of this was in the same window controller I got the feeling it was doing work that it shouldn’t have to. I started using NSViewController and came to the conclusion that it didn’t quite fit in my design, after considering how MVC should work I asked on cocoa-dev how other people use it. Sure enough, it sparked some conversation. I think that Apple has left the use of this class up to developers intentionally, maybe they will extend it in future releases, maybe having a structured controller system seems a little abstract for smaller programs, but I think it makes things easier to maintain in the long-run.

After using the class for a while I am of the mind that each view in an app could potentially have its own controller, although this would probably be overkill; the only structure that then makes sense is a tree, just like the view hierarchy. I now use these classes extensively to inform the views, for example, how they should look: the view can then draw itself based on those options it gets from its overlord.

The XS (extra special) Controllers

Our solution includes to two classes:

  1. XSWindowController, an NSWindowController subclass
  2. XSViewController, an NSViewController subclass

You can find these classes in the example project (XCode 3.0). Dowonload it here.

The Goal of This Design

The goal of our design is simple: We want a way to manage a group of view controllers in a way that fits in nicely with the current Cocoa MVC architecture.

When building a Cocoa app, the controller layer of the architecture can be described very loosely as:

  • NSDocument contains a list of NSWindowControllers
  • Each window controller has an associated window
CocoaArchitecture.jpg

We want to extend this design so that:

  • NSDocument contains a list of NSWindowControllers*
  • Each NSWindowController conains a list of NSViewControllers
  • Each NSViewController contains a list of subcontrollers
  • Each NSViewController has an associated view
XSArch.jpg

*Our changes happen beneath the document layer, so it is also a valid design for applications that aren’t document-based.

XSViewController and XSWindowController

In order to meet our goals, we enhanced Cocoa’s NSWindowController and NSViewController classes.

In XSViewController, we added a list of subcontrollers and the necessary methods to manage that list. We also gave the view controllers a reference to the window controller.

In XSWindowController, we added a list of view controllers. The window controller is the “host” for the view controllers, so when the window controller is created and destroyed by the document, it does the same to the view controllers. The window controller also does some extra work that is necessary for the view controllers to be integrated smoothly into the existing Cocoa controller architecture. We’ll describe this work further down.

In this setup, you would use the following XSWindowController methods to add and remove view controllers,

- (void)addViewController:(XSViewController *)viewController;
- (void)removeViewController:(XSViewController *)viewController;

In XSViewController, you can nest controllers and manipulate the structure of the controller tree using several methods that will be familiar to those who have worked with mutable arrays,

- (void)addChild:(XSViewController *)child;
- (void)insertObject:(XSViewController *)child inChildrenAtIndex:(NSUInteger)index;
- (void)insertObjects:(NSArray *)children inChildrenAtIndexes:(NSIndexSet *)indexes;
- (void)insertObjects:(NSArray *)children inChildrenAtIndex:(NSUInteger)index;
- (void)removeChild:(XSViewController *)child;
- (void)removeObjectFromChildrenAtIndex:(NSUInteger)index;

As long as you use these methods to add and remove view controllers from the application, you will get all of the benefits of the design.

Quick design note:

We want to note here that we considered a design where the window controller contained one view controller that would be the root of a single view controller tree. We chose to keep a list of view controllers in the window controller because it feels redundant to have to make a second controller that represents the entire window.

In a perfect world, the view controllers and window controllers would actually be the same class, so that the window controller would be the root of a single tree of controllers. This isn’t possible, but we decided that we would design with that structure in mind anyway.

Working with Cocoa

So, after we had this system set up and running, making sure that memory management was handled properly, we had to handle some Cocoa-specific behaviors so that the view controllers were well integrated into the Cocoa application architecture. This is the “glue-code” of this design. There are two Cocoa-related issues that we had to consider.

Cocoa Consideration 1: Taking care of the Responder Chain

NSViewController is a subclass of NSResponder, but it needs to be added to the responder chain to receive action events from things like buttons and menu items. We decided that our design should patch the responder chain so that it runs through the view controllers like this:

ResponderChainSmall.jpg

We looked at two approaches to solving this problem. The first approach would be to handle the responder chain in the NSViewController class, so that when a view controller was added or removed from the tree, its super controller would make sure the responder chain was patched together correctly.

The other approach is to have the window controller do the responder chain patching whenever a view controller is added or removed.

Both of these approaches have their advantages and disadvantages.

The first approach would keep things logically clean and less glue-like. The view controllers wouldn’t have to communicate back to the window controller when they add or remove their subcontrollers. If this were the perfect design world, where the window and view controllers were in the same tree, this would be the obvious way to maintain the responder chain throughout a single hierarchy of controllers.

The second approach is just more simple in this particular setup. Since this isn’t the perfect design world, the code that adds the view controllers to the responder chain would have to be repeated in both classes anyway. Letting one class handle the responder chain keeps this code centralized.

We decided to use the second approach. We don’t feel that there is a perfect solution to this problem and that either approach works fine.

The method that patches the responder chain is in XSWindowController:

- (void)patchResponderChain;

The source code will show how simple it is to keep the responder chain looking like it does in the diagram.

Consideration 2: Bindings and Observations

Bindings and Key-Value Observing are powerful Cocoa mechanisms that help us to keep our controllers and our data models separate. Most view controllers and window controllers will have bindings or KVO set up in some way.

In NSViewController, there is the idea of a “representedObject”. According to the documentation of NSViewController:

Declaring a generic representedObject property, to make it easy to establish bindings in the nib to an object that isn’t yet known at nib-loading time or readily available to the code that’s doing the nib loading.

This is a handy feature of NSViewController, especially if you are setting up all of your bindings in Interface Builder, but in a more complex setup, the single “representedObject” may not be the best way to expose a view controller to the data in an application.

There are situations where you might want to set up several KVOs and bindings in code and then remove them when you don’t need them anymore. If you forgo the “representedObject” as a means to set up KVO with your application’s data, you might come across this message in your logs when you close the document:

An instance (so-and-so) of class (so-and-so) is being deallocated while key value observers are still registered with it. Break on _NSKVODeallocateLog to start debugging.

We decided to go ahead and handle the possibility of these situations by adding a method to XSViewController called,

- (void)removeObservations;

This gives the view controllers a chance to remove observations or bindings that they set up in code before the data is released. The window controller has to manage the timing of this. In XSWindowController, we do it right before the window closes, in an implementation of the window’s delegate method,

- (void)windowWillClose:(NSNotification *)notification;

The window controller tells its view controllers to “removeObservations” here and they pass the message on to their subcontrollers. The window controller and document can then release data as they normally would in their implementations of “dealloc”.

Quick notes on subclassing:

If an XSViewController subclass implements the “removeObservations” method, it is responsible for calling super’s implementation so that the message will continue to be propagated down its branch of the tree.

If an XSWindowController subclass needs to implement “windowWillClose”, it should be sure to call super’s implementation so that the view controllers will get the message to remove their observations. The timing of this message is important, so if you are releasing some data here, be sure to call super first.

Using “windowWillClose” for a feature like this may not be the best solution, but as far as we can tell, it seems like the most convenient place to perform this task.

That’s It.

With these few enhancements, we now have two new abstract super-classes for our controllers, XSWindowController and XSViewController. When we subclass them to build our UIs, we get the controller architecture that we illustrated at the beginning of the post and the following features built in to our view controller:

  • Automatic memory management!
  • Automatic inclusion in the responder chain!!!
  • A designated method for removing observations or bindings!
  • A relationship with the window controller and document!

This design will become more and more useful as your single window interface becomes more complex, especially as your feature set changes over the life-time of your development. With this architecture in place, you have more flexibility to try things out and change your design without worrying about breaking the responder chain (which is not that easy to debug) or causing memory leaks by accident as you’re working rapidly to test UI designs. As long as you keep to MVC design principles, it is possible to create self-contained view controllers that can be plugged in to, and unplugged from, your UI with very little hassle.

Next Time…

First, thanks so much to Jonathan for working on this post with me. It was great to have the chance to brainstorm with another developer, especially one whose applications are completely different from the ones I work on every day. Working with him on this design helped to get me out of my usual mind-set and to isolate the issues that are truly common to any Cocoa application rather than unique to my own projects. This has been an educational and super-productive experience for me – Thanks, Jonathan!

AND a another big thanks to Jonathan for setting up the Xcode 3.0 example project and the source code!

In the next and last post about NSViewController, I’m going to discuss its relationship to NSView and the view hierarchy in more detail. One of the many important jobs of a view controller is to help to build and manage the view hierarchy during runtime. This is especially important when coding a single window interface that needs to give users access to many different features that can’t all be displayed in the window at one time.

Anyone who is sick of me writing about autoresizing should just skip the next installment ; ) ( or in Japanese, ^_- )

Resources

The example project contains XSWindowController and XSViewController, which contain all the nitty-gritty implementation details. There is also an example app that shows how you could subclass these classes to build a UI based on the XS controllers.

Cocoa Event-Handling Guide: The Responder Chain

Introduction to Document-Based Applications Overview

NSViewController Class Reference

NSWindowController Class Reference

Introduction to Key-Value Observing Programming Guide

Introduction to Cocoa Bindings Programming Topics

UPDATE 04/23/08

We updated the example project today. The biggest change we made is in XSViewController. We were previously setting the “representedObject” of child controllers to be that of its parent. In the new version we don’t deal with “representedObject” in any way. You can just use NSViewControllers methods to set them case-by-case.

XCode Project

Just the Source Code

Just XSViewController and XSWindowController