Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protocol paradigm in Objective -C [duplicate]

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

like image 373
TeaCupApp Avatar asked Aug 23 '11 12:08

TeaCupApp


2 Answers

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.

like image 97
Eimantas Avatar answered Oct 23 '22 08:10

Eimantas


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.

like image 4
EmptyStack Avatar answered Oct 23 '22 09:10

EmptyStack