Optional协议方法的真实示例

Optional协议方法的真实示例

本文介绍了@Optional协议方法的真实示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习Objective-C,并且遇到了协议中的可选方法.我的背景是C#,可以将Protocol看作类似于C#接口.

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.

在C#接口表示合同的情况下,通过广告宣传一个接口,您就是说您将实现所定义的方法.

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

考虑到这一点,我很困惑为什么您需要定义一个可选方法.这不是侮辱,也不是减少Objective-C的尝试,我爱Objective-C.我只是想了解这些可选方法的好处,以便对语言有更好的了解.

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.

推荐答案

我将举一个例子.我有许多与Flickr API通讯的ObjC类.一个叫做FKAccount的东西可以做很多与Flickr用户帐户有关的事情,包括下载用户的照片,获取他们的联系人列表等等.

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.

FKAccount类定义委托协议FKAccountDelegate.此协议指定FKAccount将在其委托上调用的许多回调方法,具体取决于对Flickr进行的各种网络操作的成功或失败.并非每个使用FKAccount的应用程序都会对FKAccount可以执行的每个Flickr操作感兴趣.

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.

如果要求每个声称要实现FKAccountDelegate协议的类都实现了每个方法,则最终会有很多存根方法(FWIW,在FKAccountDelegate中定义了41个方法).在协议中将这些方法声明为@optional时,委托仅需要实现其有兴趣接收的回调.

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.

FKAccount类通过以下方式检查其委托是否响应协议中的@optional方法:

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

这篇关于@Optional协议方法的真实示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:35