Swamped by Events

Code that contains multiple entry points — methods that are called through events — can be hard to read, to understand, to maintain, and to debug, even when your classes are relatively small and simple. As you develop a class that’s intended to receive more than one or two events, I recommend that you comment your code clearly, so that you know what methods you think Cocoa will be calling and why and when.

To illustrate the problem, I’ll list some of the methods in a typical class of mine. This is a small class in a small, simple app. It is a UIViewController subclass; in point of fact, it is a UITableViewController subclass, so it serves not only to load and configure the table view, but also as the table view’s delegate and data source. This is an iOS 4 app and therefore participates in multitasking. The app works with the built-in music library and music player, so there are also some notifications from the MPMusicPlayerController class. I omit the class’s designated initializer and dealloc, as well as various utility methods called by the methods I list.

Here are the methods:


An overridden UIViewController method. Called by Cocoa just after the class is instantiated. Here we create the table view and perform various other view initializations. We also add ourself as observer for four notifications:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(prepareToForeground:) name:UIApplicationWillEnterForegroundNotification object:nil]; ...

Get Programming iOS 4 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.