protocol 详解
蘋(píng)果官方文檔
- 在文檔里面有一段比較簡(jiǎn)短的解釋
A class interface declares the methods and properties associated with that class. A protocol, by contrast, is used to declare methods and properties that are independent of any specific class.
翻譯一下就是 ”一個(gè)類接口聲明與該類相關(guān)的方法和屬性,與之相比,一個(gè)協(xié)議被用來(lái)聲明獨(dú)立于任何類之外的一組方法和屬性。
簡(jiǎn)單定一個(gè)協(xié)議在 People.h 中,如下
@protocol People
@property (strong, nonatomic, readwrite) NSString *name;
@property (nonatomic) NSInteger idNumber;
-(NSString *) saySomething;
@end
定義一個(gè) Student類,Student.h 如下
#import <Foundation/Foundation.h>
@interface Student : NSObject
@end
Student.m 如下
#import “Student.h”
#import “People.h”
@interface Student()
@end
@implementation Student
@end
默認(rèn)或者在@required 之后聲明的方法要進(jìn)行實(shí)現(xiàn),對(duì)象需要聲明實(shí)例
在Student實(shí)現(xiàn)中我們會(huì)看到警告
[圖片]
第一個(gè)警告翻譯一下就是,“不會(huì)為在協(xié)議中聲明的屬性執(zhí)行自動(dòng)屬性合成“,在文檔中可以看到
The compiler does not automatically synthesize properties declared in adopted protocols.
翻譯過(guò)來(lái)就是,編譯器不會(huì)為從協(xié)議繼承過(guò)來(lái)的屬性自動(dòng)合成實(shí)例,給出修復(fù)的建議是,為屬性添加 @synthesize 聲明
第二個(gè)警告的大概意思就是 Student類未遵守 People協(xié)議
為什么會(huì)有警告,通過(guò)文檔可以看到
By default, all methods declared in a protocol are required methods. This means that any class that conforms to the protocol must implement those methods.
意思是,默認(rèn)情況下,所有被聲明在protocol的方法都是必須需要實(shí)現(xiàn)的方法, 但即使是未實(shí)現(xiàn)所有的協(xié)議指定的方法,也不會(huì)報(bào)錯(cuò),build也不會(huì)失敗,只會(huì)進(jìn)行警告
我們需要注意的是,required 和 optional 只會(huì)給出警告,運(yùn)行也只有你調(diào)用了未實(shí)現(xiàn)的方法或者變量才會(huì)報(bào)錯(cuò),更多時(shí)候是給程序員自己需要遵循的一個(gè)約定,所以作為一個(gè)合格的程序員,你應(yīng)該按照約定來(lái)寫(xiě)代碼,這樣才不會(huì)發(fā)生你預(yù)想不到的錯(cuò)誤。
將不遵循某個(gè)協(xié)議的對(duì)象賦值給其他遵循某個(gè)不遵循某個(gè)協(xié)議的對(duì)象是不符合語(yǔ)意的
By specifying the required protocol conformance on the property, you’ll get a compiler warning if you attempt to set the property to an object that doesn’t conform to the protocol, even though the basic property class type is generic.
意思就是將一個(gè)不符合協(xié)議的對(duì)象 賦值給一個(gè)屬性將會(huì)產(chǎn)生警告
[圖片]
Protocols Can Have Optional Methods 協(xié)議存在可選的方法
@optional 關(guān)鍵字后的屬性和方法可以根據(jù)需要進(jìn)行實(shí)現(xiàn)
但是需要注意的是,如果你在代碼中要使用optional的方法 function ,請(qǐng)首先用 respondsToSelector:@selector( function ) 對(duì)方法進(jìn)行檢查,看下是否對(duì)象是否對(duì)其進(jìn)行了實(shí)現(xiàn)
3. protocol 怎么用
- 第一種是委托(delegate), 比較常見(jiàn)的就是 類 UITableView 本身有一個(gè)屬性 id dataSource ,tableView 本身不實(shí)現(xiàn) 數(shù)據(jù)源的相關(guān)方法,通過(guò)外部賦值一個(gè)遵循了 UITableViewDataSource 協(xié)議的對(duì)象,執(zhí)行相應(yīng)方法來(lái)取得數(shù)據(jù)源,一般都是weak聲明的弱引用id對(duì)象,形式如下
[圖片] - 第二種就是類本身繼承一個(gè)協(xié)議,也就是如下形式, 相當(dāng)于起到了接口的作用,告訴類要實(shí)現(xiàn)哪些方法和哪些屬性。
總結(jié)
以上是生活随笔為你收集整理的protocol 详解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Python初学者(零基础学习Pytho
- 下一篇: java中System类详解