Objective-C語言允許定義協(xié)議,預(yù)計(jì)用于特定情況下的聲明方法。協(xié)議的實(shí)現(xiàn)在符合該協(xié)議的類。
一個(gè)簡單的例子將是一個(gè)網(wǎng)絡(luò)URL處理類,它將有委托方法processCompleted 一次調(diào)用類網(wǎng)絡(luò)URL抓取操作的方法,如一個(gè)協(xié)議。
協(xié)議語法如下所示。
@protocol ProtocolName @required // list of required methods @optional // list of optional methods @end
@required 關(guān)鍵字下的方法必須符合協(xié)議類實(shí)現(xiàn), @optional 關(guān)鍵字下的可選方法來實(shí)現(xiàn)。
這是符合協(xié)議的語法類
@interface MyClass : NSObject <MyProtocol> ... @end
這意味著,MyClass的任何實(shí)例響應(yīng)不僅是具體在接口聲明的的方法,而 MyClass 的 MyProtocol 所需的方法也提供了實(shí)現(xiàn)。也沒有必要再聲明協(xié)議類接口的方法 - 采用的協(xié)議是足夠的。
如果需要一個(gè)類來采取多種協(xié)議,可以指定他們作為一個(gè)逗號(hào)分隔的列表。我們有一個(gè)委托對(duì)象,持有調(diào)用對(duì)象的參考,實(shí)現(xiàn)了協(xié)議。
一個(gè)例子如下所示。
#import <Foundation/Foundation.h> @protocol PrintProtocolDelegate - (void)processCompleted; @end @interface PrintClass :NSObject { id delegate; } - (void) printDetails; - (void) setDelegate:(id)newDelegate; @end @implementation PrintClass - (void)printDetails{ NSLog(@"Printing Details"); [delegate processCompleted]; } - (void) setDelegate:(id)newDelegate{ delegate = newDelegate; } @end @interface SampleClass:NSObject<PrintProtocolDelegate> - (void)startAction; @end @implementation SampleClass - (void)startAction{ PrintClass *printClass = [[PrintClass alloc]init]; [printClass setDelegate:self]; [printClass printDetails]; } -(void)processCompleted{ NSLog(@"Printing Process Completed"); } @end int main(int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; SampleClass *sampleClass = [[SampleClass alloc]init]; [sampleClass startAction]; [pool drain]; return 0; }
現(xiàn)在,當(dāng)我們編譯并運(yùn)行程序,我們會(huì)得到以下的結(jié)果。
2013-09-22 21:15:50.362 Protocols[275:303] Printing Details 2013-09-22 21:15:50.364 Protocols[275:303] Printing Process Completed
在上面的例子中,我們已經(jīng)看到了如何調(diào)用和執(zhí)行的delgate方法。啟動(dòng)startAction,一旦這個(gè)過程完成后,被稱為委托方法processCompleted 操作完成。
在任何 iOS 或 Mac應(yīng)用程序中,我們將永遠(yuǎn)不會(huì)有一個(gè)程序,沒有委托實(shí)現(xiàn)。所以我們理解其重要委托的用法。委托的對(duì)象應(yīng)該使用 unsafe_unretained 的屬性類型,以避免內(nèi)存泄漏。