Re: Why use protocols?
Re: Why use protocols?
- Subject: Re: Why use protocols?
- From: Matt Neuburg <email@hidden>
- Date: Wed, 18 May 2005 10:07:21 -0700
On Wed, 18 May 2005 11:11:12 -0400, "Ben D. Jones" <email@hidden>
said:
> This is a newbie question I'm sure, but I'm really not clear on
>this concept. Coming from a C background the concept of protocols
>isn't very clear. Objective-C is my first truly OOP language and
>maybe I'm not understanding OOP correctly. My question is... if
>you have a class and protocol like this:
>
> @interface MyClass : NSObject <MyProtocol>
>{ @protocol UpDown
> NSString
>*aString;
> - (void)increment;
> }
> -(void)decrement;
> - (void)
>doStuff;
> @end
> - (id)doMoreStuff:(NSString *)withAString
>
>isn't that clear enough to put the methods of that protocol in the
>MyClass def without the use of a protocol to "make sure it conforms
>to a protocol" ?
Here's an example. I've subclassed NSTableColumn in order to override
dataCellForRow:. But I don't think it's my NSTableColumn subclass's job to
contain the implementation; it's my table data source's job. So all my
NSTableColumn subclass does is turn to the data source to get the answer:
@implementation MyTableColumn
- (id)dataCellForRow:(int)row {
id ourDataSource = [[self tableView] dataSource];
return [ourDataSource dataCellForRow: row sender: self];
}
@end
Now, how do we know that ourDataSource (which, it is important to stress,
could be any class whatever) implements dataCellForRow:sender:? And how does
the compiler know? A protocol solves both problems at once. It prevents the
programmer from forgetting to implement dataCellForRow:sender: in the data
source class (it would be a disaster if the programmer forgot to do this);
and it shuts the compiler up by satisfying it that ourDataSource does in
fact implement it.
@protocol MyTableColumnDataSource
- (id) dataCellForRow: (int) row sender: (id) self;
@end
@implementation MyTableColumn
- (id)dataCellForRow:(int)row {
id <MyTableColumnDataSource> ourDataSource = [[self tableView]
dataSource];
return [ourDataSource dataCellForRow: row sender: self];
}
@end
This isn't the only solution to this problem, by any means, but it is an
easy quick one. So the answer to your question really is: the use of
protocols will become clearer to you as you actually start doing to some
serious programming with Cocoa and discover how protocols help you with the
way your objects are organized and the way the Cocoa framework and messaging
model are structured. m.
--
matt neuburg, phd = email@hidden, <http://www.tidbits.com/matt/>
A fool + a tool + an autorelease pool = cool!
AppleScript: the Definitive Guide
<http://www.amazon.com/exec/obidos/ASIN/0596005571/somethingsbymatt>
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden