协议(protocol)

Protocol

You have learned about the basic elements and structure of Objective-C classes, but the language provides several additional features for developing classes. In this section, you’ll learn about one of these: protocols. A protocol declares methods and properties that can be implemented by any class. A class interface is directly associated with a specific class and, hence, a class hierarchy. On the other hand, a protocol is not associated with any particular class, thus it can be used to capture similarities among classes that are not hierarchically related. Protocols provide Objective-C with the capability to support the concept of multiple inheritance of specification (i.e., of method declarations). A protocol can also be used to define the messages that an object can send (by specifying properties that conform to a protocol).


objective-c 提供了协议这种特性。 

协议中声明了可以被任何类实现的方法和属性。

协议不是跟某个特定的类关联的,而是在类之间用来捕获相似的但与类的层级不相关的地方,多个不相关的类都遵守这个协议。

协议使得object-c可以实现多继承。

协议也可以被用来定义对象发送的消息(通过指定属性遵守协议)


Syntax

A protocol declaration begins with the @protocol directive followed by the name of the protocol.It ends with the @end directive. Protocols can have both required and optional methods; optional methods do not require that an implementation of the protocol implement these methods. The directives @required and @optional (followed by the method name(s)) are used to mark a method appropriately. If neither keyword is specified, the default behavior is required. The syntax of a protocol declaration is shown in Listing 2-12.

协议语法

@protocol 协议名
	@required(默认的):
              方法
        @optional:
             方法
@end


One protocol can incorporate other protocols by specifying the name of each declared protocol within braces; this is referred to as adopting a protocol. Commas are used to separate multiple protocols (see Listing 2-13).

协议可以跟其他协议进行合并:

@protocol 协议名<协议名,协议名,..>
     // Method declarations
@end


An interface can adopt other protocols using similar syntax .

接口采用协议跟上面类似:

@interface 类名: 父类名字 <span style="font-family: Arial, Helvetica, sans-serif;"><协议名,协议名,..></span>
// Method declarations
@end







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值