A Delegate is an object that takes care of some set of tasks for another object. Typically, the object with the delegate is a general object, with the delegate being providing application- or task-specific behavior or data. Cocoa uses this pattern for a variety of user interface classes: the delegate handles application-specific behavior or provides data to the UI object. The NSWindowDelegate protocol gives your application or document a chance to respond to events like window resizing or closing, perhaps cancelling the operation if necessary. The NSTableViewDelegate protocol lets your application respond to the user’s interactions with the table. The table may ask your application (probably through a controller of some sort) for data to display, or it may tell your application that the user has changed the data.
This chapter uses the class MYBarView, which is much like the MYBarView class from Chapter 3. This one doesn’t have a label, but it uses a delegate to control the bar fraction.
MYBarView defines a MYBarViewDelegate protocol that has the methods barView:shouldChangeValue, barViewWillChangeValue: and barViewDidChangeValue:.
The program has five MYBarView sliders: three that were directly connected to sliders and that used the MYLimitChanger delegate to turn the bar from gray to black when the the bar’s value was above 0.75. The other two were controlled by a single slider: one directly and the other by a MYValuePropagator delegate that took a value from the first slider and sent it to the second.
The bars didn’t act correctly at first: the directly controlled bars were always completely filled, and the ones that used the MYLimitChanger delegate were always white. Moving the sliders didn’t change anything. I checked the code without finding any problems, but checking the connections revealed one of the problems: the bars in the box weren’t set up properly. Fixing that only turned them both black.
Setting a break point in takeBarValueFrom: showed that the value set by the slider was well above 1.0. Going back to IB revealed that the sliders still had the default range of 0 to 100. Changing them all to range from 0 to 1 fixed everything.
The moral of the story: pay attention to those default values that IB provides for you. They’re not necessarily bad choices, but they may not work for your application.