protocol 详解
蘋果官方文檔
- 在文檔里面有一段比較簡短的解釋
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.
翻譯一下就是 ”一個類接口聲明與該類相關的方法和屬性,與之相比,一個協(xié)議被用來聲明獨立于任何類之外的一組方法和屬性。
簡單定一個協(xié)議在 People.h 中,如下
@protocol People
@property (strong, nonatomic, readwrite) NSString *name;
@property (nonatomic) NSInteger idNumber;
-(NSString *) saySomething;
@end
定義一個 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
默認或者在@required 之后聲明的方法要進行實現(xiàn),對象需要聲明實例
在Student實現(xiàn)中我們會看到警告
[圖片]
第一個警告翻譯一下就是,“不會為在協(xié)議中聲明的屬性執(zhí)行自動屬性合成“,在文檔中可以看到
The compiler does not automatically synthesize properties declared in adopted protocols.
翻譯過來就是,編譯器不會為從協(xié)議繼承過來的屬性自動合成實例,給出修復的建議是,為屬性添加 @synthesize 聲明
第二個警告的大概意思就是 Student類未遵守 People協(xié)議
為什么會有警告,通過文檔可以看到
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.
意思是,默認情況下,所有被聲明在protocol的方法都是必須需要實現(xiàn)的方法, 但即使是未實現(xiàn)所有的協(xié)議指定的方法,也不會報錯,build也不會失敗,只會進行警告
我們需要注意的是,required 和 optional 只會給出警告,運行也只有你調(diào)用了未實現(xiàn)的方法或者變量才會報錯,更多時候是給程序員自己需要遵循的一個約定,所以作為一個合格的程序員,你應該按照約定來寫代碼,這樣才不會發(fā)生你預想不到的錯誤。
將不遵循某個協(xié)議的對象賦值給其他遵循某個不遵循某個協(xié)議的對象是不符合語意的
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.
意思就是將一個不符合協(xié)議的對象 賦值給一個屬性將會產(chǎn)生警告
[圖片]
Protocols Can Have Optional Methods 協(xié)議存在可選的方法
@optional 關鍵字后的屬性和方法可以根據(jù)需要進行實現(xiàn)
但是需要注意的是,如果你在代碼中要使用optional的方法 function ,請首先用 respondsToSelector:@selector( function ) 對方法進行檢查,看下是否對象是否對其進行了實現(xiàn)
3. protocol 怎么用
- 第一種是委托(delegate), 比較常見的就是 類 UITableView 本身有一個屬性 id dataSource ,tableView 本身不實現(xiàn) 數(shù)據(jù)源的相關方法,通過外部賦值一個遵循了 UITableViewDataSource 協(xié)議的對象,執(zhí)行相應方法來取得數(shù)據(jù)源,一般都是weak聲明的弱引用id對象,形式如下
[圖片] - 第二種就是類本身繼承一個協(xié)議,也就是如下形式, 相當于起到了接口的作用,告訴類要實現(xiàn)哪些方法和哪些屬性。
總結
以上是生活随笔為你收集整理的protocol 详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python初学者(零基础学习Pytho
- 下一篇: JS 转换格林尼治时间