Question

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.

Was it helpful?

Solution

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];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top