One concept that pops up frequently in Cocoa programming is that of delegation. In fact, we’ve already seen that concept in my previous post about NSOutlineView. We set the delegate of our NSOutlineView to be the TodoController. We also set the data source to be TodoController—a data source is just another delegate.
A delegate is described as a person who acts on behalf of another, and this is pretty much exactly what it sounds like in Cocoa. When we set a delegate (or data source) of an object which accepts one, we’re telling the object to pass a certain amount of control over to the object we specify. The delegate is acting on behalf of (performing some of the function of) the original object.
That’s all well and good, but how does the delegate know what to do? That’s where protocols come in.
In Objective-C, protocols describe the methods that delegates can or must implement in order to perform the activities they’ve been delegated to do. They don’t have to implement those methods, but incomplete implementations may mean that things don’t work correctly. This is particularly important for things like data sources, where they’re asked to provide actual data to be displayed to the screen: if you don’t implement them right, the data doesn’t get delivered.
Once we’ve implemented those methods, and set our delegates correctly (either in Interface Builder or programmatically), our original object can then call those methods on the delegate to handle those functions.
In the case of our NSOutlineView, one of those methods was outlineView:viewForTableColumn:item:. This method took the task of creating a view which could be returned to the NSOutlineView to be displayed on the screen. If we didn’t implement this method, as we found out, nothing would appear on the screen; it’s a required method for NSOutlineViewDelegate protocol.
Although there are four required delegate methods to programmatically get an NSOutlineView to display data, there are many other methods that can be implemented to customise the behaviour of the outline view. One of these methods is, for example, outlineViewItemDidExpand:. If we implemented this method in our delegate, we can customise the behaviour or perform certain actions that happen after a group is expanded. We will actually need to do this in order to store the expanded state with our groups. This method is not required—leaving it out will have no effect on the function of the outline view—but implementing it gives us greater control over the function of our application.
Anyway, that’s a basic rundown of how delegation and protocols work in Objective-C/Cocoa. It’s a very powerful way to customise function without subclassing objects.
Pingback: Concepts: Delegation and protocols | Ben Reimers | effort.ly