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.
I’ll give you an example. I have a number of ObjC classes that talk to the Flickr API. One, called
FKAccountcan 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
FKAccountclass defines a delegate protocolFKAccountDelegate. This protocol specifies a number of callback methods thatFKAccountwill invoke on its delegate depending on the success or failure of various network operations to Flickr. Not every application that usesFKAccountwill be interested in every Flickr operation thatFKAccountcan perform.If it were required that every class claiming to implement the
FKAccountDelegateprotocol implemented every method, you would end up with a lot of stub methods (FWIW, there are 41 methods defined inFKAccountDelegate). When these methods are declared@optionalin the protocol, the delegate only need implement the callbacks it is interested in receiving.The
FKAccountclass checks that its delegate responds to@optionalmethods in the protocol by: