views:

897

answers:

1

I'm learning Objective-C at the moment and have come across optional methods in Protocols. My background is C# and can see a Protocol as something similar to a C# Interface.

Where a C# Interface represents a contract, by advertising an Interface you are saying that you will implement the methods defined.

With this in mind I'm confused why you would ever need to define an optional method. This is not slur or an attempt to lessen Objective-C, I love Objective-C. I simply want to understand the benefits of these optional methods, in order to gain a greater understanding of the language.

I'd really appreciate it if someone could provide some real world scenarios (with sample code) where optional methods are useful.

+5  A: 

I'll give you an example. I have a number of ObjC classes that talk to the Flickr API. One, called FKAccount can do lots of things related to a Flickr user's account including downloading the user's photos, getting their contact list and so on.

The FKAccount class defines a delegate protocol FKAccountDelegate. This protocol specifies a number of callback methods that FKAccount will invoke on its delegate depending on the success or failure of various network operations to Flickr. Not every application that uses FKAccount will be interested in every Flickr operation that FKAccount can perform.

If it were required that every class claiming to implement the FKAccountDelegate protocol implemented every method, you would end up with a lot of stub methods (FWIW, there are 41 methods defined in FKAccountDelegate). When these methods are declared @optional in the protocol, the delegate only need implement the callbacks it is interested in receiving.

The FKAccount class checks that its delegate responds to @optional methods in the protocol by:

if([self.delegate respondsToSelector: @selector(accountDidDownloadContacts:)]) {
    [self.delegate accountDidDownloadContacts: self];
}
Fraser Speirs
I think I'm getting it now. A C# Interface is only one facet of an Objective-C Protocol. You can use a Protocol as a contract, but these optional methods constitute a list of optional delegates that an object can choose to respond too. That's really interesting.
kim3er
+1 for using a protocol to document delegate functions
Tom Dalling
I totally agree with @Tom. Prior to Objective-C 2.0, delegate methods were usually declared in a category on NSObject to avoid any class that wants to be a delegate from having to implement all the methods. Optional methods in protocols is a much cleaner solution that doesn't tack tons of methods onto NSObject, and helps avoid method collisions. If only Java had optional interface methods, there would be no need for things like inheriting from MouseAdapter. Using classes like that are usually the few times that I've cursed single inheritance... :-)
Quinn Taylor