协议(protocol)

来源:互联网 发布:微云同步盘mac版 编辑:程序博客网 时间:2024/05/23 01:14
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
原创粉丝点击