8

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

0

8 Answers 8

6

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.

0
4

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.

1
  • Very descriptive, However I have to accept Eimantas answer as he gave it first, But thanks
    – TeaCupApp
    Aug 23, 2011 at 13:08
4

Protocols are often used to give a class certain functionality. But it is not always necessary that all methods in a protocol are defined for a certain task. The methods that are not required everywhere for a class to "be" a certain protocol are optional.

Protocols are often used to define delegates. To make a class a possible delegate (more or less like a callback) of another class, it must respond to certain messages (method invocations) defined in a protocol. For some occasions, certain methods of the delegate will never be called, since they don't apply to the situation and setup. Such methods can be made optional in the protocol, so they don't have to be implemented in the delegate. If they were all required, like in Java, they would probably be implemented as empty methods anyway.

The fact that methods are invoked dynamically makes this a lot easier, I guess. A class invoking the delegate can actually check if a method is implemented on the delegate, or not, before it tries to invoke it.

7
  • It's important to note that classes which don't implement that method but do implement that interface will simply do nothing when passed that message.
    – N_A
    Aug 23, 2011 at 12:54
  • 1
    methods are invoked dynamically makes this possible. In short, Objective-C has @optional protocol methods, just because it can .)
    – Eimantas
    Aug 23, 2011 at 12:55
  • @mydogisbox: nice point to ponder.
    – viral
    Aug 23, 2011 at 13:07
  • @mydogisbox: Can't try this right now (I'm writing this on an old Windows laptop), but I guess you'd get an exception. I am glad to be proven wrong, in this respect, though. Aug 23, 2011 at 13:11
  • Thanks first answer which enlighten me was answered by Eimantas's so I accepted his answer as all answer were pretty similar. However it must be really hard to just see that if some class implements xyz protocol than big question arises does it implement 1111 or 2222 method which are optional? does compiler give a signal or it just sits their and do nothing?
    – TeaCupApp
    Aug 23, 2011 at 13:14
2

As answered Real world examples of @optional protocol methods an optional method in the protocol could be triggered after a particular series of events. To still conform to the protocol and implement it you only need the required methods and adds flexibility.

Also see apple documentation on protocols http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProtocols.html#//apple_ref/doc/uid/TP30001163-CH15-TPXREF148

Note that it's not really the same as a java interface since a class may implement a protocol without being declared to implement it.

2
  • Thanks, It looks like this could be considered as duplicate but both question are different :)
    – TeaCupApp
    Aug 23, 2011 at 13:09
  • 1
    Yeah I was more pointing out the answer for the other question had some relevance and might be useful :)
    – Alex Jones
    Aug 23, 2011 at 13:25
2

Protocol defines methods that your class conforms to when doing certain tasks, usually being a delegate of other class' instance.

For example, UITableViewDataSource protocol defines methods like - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; and - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;

First one is required, and other is optional. Because table view needs to know how many rows to display, but it doesn't need to know how many sections (it will default to 1 section). So the second method is declared under @optional in UITableView.h. When you create a class that will act as table view's data source, you define it as @interface ClassName : SuperClassName <UITableViewDataSource> which tells the compiler your class conforms to this protocol.

If you don't implement the first method, compiler will tell you you have incomplete implementation, but if you don't implement second one, code will build and run without warning.

2

Objective-C protocols are indeed similar to Java Interfaces. They provide a level of abstraction that enables polymorphism in any classes that use your protocol enabled class. This means that any classes that use one of your protocol implementations can be sure that specific methods are available.

Optional methods are just what they say they are: optional. Any class that adopts a protocol MAY implement these methods, but they are not essential.

The use of protocols is most useful when you are implementing a Delegate design pattern. Whenever you are declaring a delegate for a class or callback method, enforcing that a delegate conforms to a protocol ensures that all of the necessary callbacks are available. In UI development, this often ensures that your views will respond appropriately to updated datastores or network events.

2
//Not all ducks can fly.  

But, Some do.
So @optional is for those, who can fly, to be implemented.

In real world some methods need to be implemented for some classes, need not for all.
In Objective C, Implementor of protocol can give flexibility to programmer to decide whether to implement the method for customization of class or not,using @optional.

Best example is UITableViewDataSource.

2

I am writing a HTTPRequest framework which has a protocol with methods like below which needs to be implemented by the class which is using my framework to upload/download a file,

@protocol HTTPRequestDelegate
@required
-(void)HTTPRequestSuccessWithData:(NSDictionary *)inDictionary;
-(void)HTTPRequestFailedWithError:(NSError *)inError;
@optional
-(void)fileUploadPercentage:(NSInteger)inPercent;
@end

Now here the class which uses my framework to upload/download a file has to implement the @ required methods to get the result of the upload/download but it can implement the @optional method only if it needs, here if the class wants to display the upload/download percentage in some progress indicator it has to implement the fileUploadPercentage: method also. If the class doesn't bother about the completed percentage then no need of implementing that method. Hope this helps.

1
  • Thanks btw you are bit late however 1+ for your effort mate!
    – TeaCupApp
    Aug 23, 2011 at 13:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.