本節目錄atom
protocol是協議的意思,能夠理解成定義規則,就是你必須跟着個人規則走,不然不是亂套了對吧。spa
咱們添加一個Button類,聲明一個Button監聽的協議,而後用戶經過這個協議來實現按鈕監聽代理
Button.hcode
#import <Foundation/Foundation.h> //聲明一個代理,後面才定義 @protocol ButtonDelegate; @interface Button : NSObject //按鈕的點擊方法 -(void)click; //代理就是監聽器,當用戶點擊時經過代理通知用戶 @property(nonatomic,assign)id<ButtonDelegate> delegate; @end //按鈕代理方法 @protocol ButtonDelegate <NSObject> //@optional; -(void)onClick:(Button *)btn; @end
Button.mblog
#import "Button.h" @implementation Button -(void)click{ //經過代理通知用戶點擊 if ([_delegate respondsToSelector:@selector(onClick:)]) { [_delegate onClick:self]; } } @end
MyButtonListener.h事件
#import <Foundation/Foundation.h> #import "Button.h" @interface MyButtonListener : NSObject<ButtonDelegate> @end
MyButtonListener.mit
#import "MyButtonListener.h" @implementation MyButtonListener -(void)onClick:(Button *)btn{ NSLog(@"MyButtonListener 監聽到按鈕的點擊事件了"); } @end
main.mio
#import <Foundation/Foundation.h> #import "Button.h" #import "MyButtonListener.h" int main(int argc, const char * argv[]) { @autoreleasepool { //聲明一個按鈕 Button *btn = [[[Button alloc] init] autorelease]; //聲明一個按鈕的監聽事件,這個監聽是遵循了ButtonDelegate協議的 MyButtonListener *listener = [[[MyButtonListener alloc] init] autorelease]; //給按鈕設置監聽 btn.delegate = listener; [btn click];//模擬屏幕點擊 } return 0; }
注:class
>protocol的聲明協議必須遵循<NSObject>協議import
>在property中用id<代理>,變量名不用加*
>聲明代理方法使用@optional修飾時,表示遵循該代理類能夠不實現代理的方法。