Tuesday, April 7, 2009

Using Delegates in Objective-C

I was following a tutorial on implementing UIPickerViews. For those who have seen or used an iPhone, it's the control that looks like a collection of spinning wheels. The approach Apple takes with the implementation of that particular control is that you must specify a Delegate and a Datasource for the control to function properly. In code, it looks like this:
@interface MyController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource> { ... } @end

The tutorial continued to walk me through NIB creation and, most importantly, connecting the NIB objects to the class. Spoiler alert: What I'm writing about is that I failed to realize three important concepts:

  1. the delegate and datasource declarations were standard components of the framework,
  2. those declarations provide a clue to the NIB that you can "control-drag" to specify the delegate class,
  3. you must "override" certain methods to guarantee that the code compiles properly

When I was running through the tutorial, I was under the preconception that the delegate class the authors were referring to was a *custom* class so I was already behind the 8-ball on point #1. I got point #2 easily enough but then failed to understand where the methods in point #3 came from. This is definitely one of those "you had to have been there" moments. I'm sure you're yawning by now...

Suffice it to say that I found my answer when I looked up UIPickerViewDataSource and UIPickerDelegate in the Apple documentation. The instance methods described should be overridden with custom treatment.

No comments:

Post a Comment