Possible Duplicate:
Real world examples of @optional protocol methods
Recently I started getting my head around objective C. So far I have started writing simple codes which all newbie does to understand how programming model works. However, When I started learning about protocol I suddenly got confused.I am basically from java
background, So I was thinking **protocol must be similar as Interface
.
So the question about protocol is,
Why a protocol needs a optional functions? like code below,
@protocol DuckProtocol
@required
-(void) quack;
@optional
-(void) fly; //Not all ducks can fly
@end
Above code didn't helped me to understand, The purpose of having protocol(interface in java) is to constraint programmer to make sure they have all listed method implemented inside the class which implements this protocol. Than why we need @optional
?
If any one have ever used this, Could you please share your thoughts regarding how this paradigm helped you?
Thanks
My approach to @optional
is that it allows guaranteed (but unnecessary) customization of object's behavior. Consider UITableViewDataSource
protocol. It has 11 methods although to make a functional table you need to implement only 2 of them. Other 9 methods are there just for table customization and Apple itself provides sensible defaults.
Simple. Objective-C gave us the provision to skip the implementation of methods we don't need.
Consier KeyListener
in Java. If you implement it, you have to implement all the methods keyPressed(KeyEvent e), keyReleased(KeyEvent e), and keyTyped(KeyEvent e), even though you don't need all of them.
But, in Objective-C you can specify @optional
methods to omit unnecessary method implementations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With