Re: What is a Delegate?
Re: What is a Delegate?
- Subject: Re: What is a Delegate?
- From: dreamcat7 <email@hidden>
- Date: Mon, 8 Sep 2008 11:39:05 +0100
Hi
Often people see "delegate method" in the Cocoa documentation and
believe they cant use those ones because it requires a special object
that they dont have.
However delegation is a very useful programming method.
Usually another developer writes a library class that requires a
delegate to filling in the missing functions. Much like the idea of of
asking you to write a callback function to fill-in the spaces that
they cannot know. The delegate methods they ask for must each have a
clearly defined purpose that is documented. They are called at
convenient times on the 'partner' object which you (probably are
already writing).
A delegate is needed for a persistent object that needs more
information from you at an unspecified time, and well after the object
was created / initialized.
And this allows the class to avoid having many or complex initializer
(that may never be used). By contrast, a delegate method can be
optional and simply ignored if it is not needed.
The best way to learn the concept delegation is to use the
NSURLConnection class in synchronous mode. Another common class which
should be attempted with delegation is NSTableView. I strongly
recommend to try either of these and then put a breakpoint in the
delegate function.
The way a library class declares its additional delegate interface
with the NSObject informal protocol. This is just a category extension
of NSObject. So as long as your object is inherited from NSObject then
you can implement these delegate methods.
@interface NSObject (ServiceProviderInformalProtocol)
// Delegate Methods
- (BOOL)serviceProviderWillRespondNextEvent:(ServiceProvider*)sender;
- (void)serviceProviderDidSetNextEvent:(ServiceProvider*)sender;
- (NSArray*)object:(ServiceProvider*)sender requiresMoreData:
(NSData*)data;// If nil, the action will stop
- (NSComparisonResult)wasEqual:(ServiceProvider*)sender;
@end
If you implement a delegate method in your own object, the library
class will try to call the delegate method when they require more
data, when an event occur or to finish the job. Dont worry, in most
cases the domumentation will tell you all you need to know.
So really when people talk about delegation in Cocoa they mean this
callback interface and not a special kind of a niche object that you
are required to write.
If you are migrating to Cocoa from another language, you may have seen
this concept already, such as X-Windows API or Java @interface.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden