一、協議的具體用法
協議的具體用法就是使用代理。代理設計模式相當於C#當中的委托。
二、如何實現代理
這里介紹一個案例
三、代理兩端如何通訊
代理兩段的通訊業就是說代理端和被代理端如何通訊的。
四、調用前后順序的問題
如果說你要調用一個協議,但是你在調用的時候你的協議還沒有聲明,所以程序會報錯,解決辦法有2個,第一,可以在前面聲明一下,例如:@protocol DogBark;放在#import <Foundation/Foundation.h>下面。第二,前向聲明可以聲明類,例如,class Dog; 如果我們把協議聲明放到了前面,但是類的聲明在我們聲明的后面,那樣又會報錯,所以解決辦法是我們在前面加一個類的聲明。
五、demo
dog.m

#import "Dog.h" @implementation Dog @synthesize ID = _ID; @synthesize delegate; - (id) init { self = [super init]; if (self) { timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES]; // 創建一個定時器 每個1.0s就調用 [self updateTimer:nil]; } return self; } - (void) updateTimer:(id)arg { barkCount++; NSLog(@"dog bark %d", barkCount); // 通知狗的主人 // delegate; [delegate bark:self count:barkCount]; // 調用delegate里面的 bark:count: 方法 // 向主人回報 } @end
dog.h

#import <Foundation/Foundation.h> @class Dog; // @class表示前向申明一個類 // 定義一個人和狗通訊的方式 protocol @protocol DogBark <NSObject> - (void) bark:(Dog *)thisDog count:(int)count; @end @protocol DogBark; // @protocol表示 協議前向申明 @interface Dog : NSObject { NSTimer *timer; int barkCount; int _ID; id <DogBark> delegate; // ownner 狗的主人 } @property int ID; @property (assign) id <DogBark> delegate; @end
Person.m

#import "Person.h" @implementation Person @synthesize dog = _dog; - (void) setDog:(Dog *)dog { if (_dog != dog) { [_dog release]; _dog = [dog retain]; // 通知_dog的主人是 self [_dog setDelegate:self]; } } - (Dog *) dog { return _dog; } - (void) bark:(Dog *)thisDog count:(int)count { // 當狗叫的時候來調用 xiaoLi人的這個方法 NSLog(@"person this dog %d bark %d", [thisDog ID], count); } - (void) dealloc { self.dog = nil; [super dealloc]; } @end
Person.h

#import <Foundation/Foundation.h> #import "Dog.h" @interface Person : NSObject <DogBark> { Dog *_dog; } @property (retain) Dog *dog; @end