Objective-C 协议(protorcol)

来源:互联网 发布:剑灵萝莉捏脸数据 编辑:程序博客网 时间:2024/05/16 06:31

Objective-C 没有像C++那样可以使用多继承,但是由想要拥有各类的方法,同时还要兼顾低耦合,这个时候引入了协议(protorcol)。

今天去苹果官方查看API,发现这样的图觉得挺好看。

协议

我们先看一下苹果多协议的描述:

https://developer.apple.com/library/content/documentation/General/Conceptual/DevPedia-CocoaCore/Protocol.html#//apple_ref/doc/uid/TP40008195-CH45-SW1

A protocol declares a programmatic interface that any class may choose to implement. Protocols make it possible for two classes distantly related by inheritance to communicate with each other to accomplish a certain goal. They thus offer an alternative to subclassing. Any class that can provide behavior useful to other classes may declare a programmatic interface for vending that behavior anonymously. Any other class may choose to adopt the protocol and implement one or more of its methods, thereby making use of the behavior. The class that declares a protocol is expected to call the methods in the protocol if they are implemented by the protocol adopter.

协议(protocol)是Objective-C重要的语言特性任何类都可以实现接口,在不使用继承可以拥有两个类的方法。遵守协议实现协议的方法我们先看代码

@protocol PersonDelegate <NSObject>  @required  -(void) personSay();  @optional  -(void) personHas();  @end  

@protocol

定义协议使用@protocol 后接协议名 ,NSObject在这里也是协议定义了协议的基本函数比如:performSelector, isKindOfClass, respondsToSelector, conformsToProtocol, retain, release 等。

@required

表示定义的协议的调用者必须实现的协议。

@optional

表示定义的协议可选协议,实现和不实现都可以

通过下面简单的例子来了解,有Person类,其他属性不列举,不同人说不同的话,做不同的是我们通过代理来让不同的人做不同的事。

@interface Person:NSObject{   id<PersonDelegate > delegate;}@property(assign,nonatomic) id<PersonDelegate> delegate;@end@impementation Person-(void)printPersonSay{    [delegate personSay];}@end

定义一个类遵守协议:比如现在有类TeachClass,一下是遵守协议的几种方式

@interface TeachClass <PersonDelegate>@interface TeachClass :NSObject<PersonDelegate>  @interface TeachClass :NSObject<PersonDelegate, NSCoding> 

实现协议协议方法只要在@impementation下实现协议方法

@impementation TeachClass //MARK: - PersonDelegate-(void) personSay() {    print(@"好好学习,天天向上");}@end

遵守协议如果不实现,编译器会警告,编译报错。

协议在Objective-C中必不可少,我们在开发UITableView,其中UITableViewDelegate和UITableViewDataSource这两个协议完成对tableView的设置,还有UITextField,UINavigation等等。

在实际开发中,为了结构清晰,我们常常定义协议来完成对应的内容。这里面涉及到多态的知识,比如Person有printPersonSay()这样的方法,但是我们不知道每个人都说什么,我们通过协议让需要说的人去遵守代理告诉我们要说什么。以上内容有错误请留言或者微博。

0 0