Real world examples of @optional protocol methods

你离开我真会死。 提交于 2019-12-04 03:08:27

问题


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.


回答1:


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];
}


来源:https://stackoverflow.com/questions/1102984/real-world-examples-of-optional-protocol-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!