Custom Delegates in Cocoa
Posted by rekle on Jan 04 2007 in Cocoa
A delegate is a kind of 'helper class' in Cocoa. Very often in Cocoa, you won't subclass a class, instead you'll just use the base class and register yourself as a delegate. This means that whenever interesting events happen in the base class, it calls a method on the delegate. The return value of this delegate function allows you to notify the calling class to stop or continue various operations.
Of course, you can create your own classes in Cocoa. This means that there needs to be a way to add support for delegate processing in your custom class. Here are the steps necessary to make this work.
- Declare the delegate variable and accessor methods in your class' header file. Note that these accessor methods should follow the standard Cocoa Key Value Coding scheme.
@interface ClassName : NSObject { id delegate; } - (void)setDelegate:(id)val; - (id)delegate; @end
- Define the accessor functions in your implementation file.
@implementation ClassName - (void)setDelegate:(id)val { delegate = val; } - (id)delegate { return delegate; } @end
- Create an informal protocol that contains all the delegate functions that your class will call in the delegate object. This informal protocol is implemented as a Category on the NSObject class. Note that the delegate will work without this step, but if you leave this out, XCode will generate a lot of "warning: no '-XXX' method found" warning messages. Also, your class that acts as the delegate of this class does not have to implement all these delegate functions. It only has to implement the methods that it is interested in. The rest will simply be ignored.
@interface NSObject (ClassName) - (void)delegateFunction1; - (void)delegateFunction2; // etc... @end
- Before calling a delegate method, make sure the delegate supports that method by using the respondsToSelector: message.
- (void)someMethod { if ( [delegate respondsToSelector:@selector(delegateFunction1:)] ) { [delegate delegateFunction1]; } }