Objective-c the Protocol
Protocol
In a nutshell, a list of methods that are declared can be implemented by whatever class, usually called (delegation) mode.
In iOS and OS X, Apple uses a number of proxy modes to implement view (UI controls) and controller (controllers) in MVC
Here's a sample example
Declares a button class and a Buttonlisterner class
In the Button.h file
#import <foundation/foundation.h>//class declaration @class button;//<> represents the implementation of a protocol, nsobject to make a fundamental agreement// Buttondelegate is the name of the protocol @protocol buttondelegate<nsobject>-(void) OnClick: (button*) but; @end @interface Button: Nsobject//nonatomic does not require multi-threading management, delegate is a button listener @property (nonatomic,retain) id<buttondelegate> delegate;-( void) Click; @end
In the button.m file
#import "Button.h" @implementation button//-(void) dealloc{// [Super dealloc];//}-(void) click{ NSLog (@ " Clickbutton was clicked ..."); Suppose there is an OnClick: The method calls this method if ([_delegate respondstoselector: @selector (OnClick:)]) { //and tells the Listener which button was clicked [_delegate onclick:self]; } } @end
In the Buttonlisterner.h file
#import <Foundation/Foundation.h> #import "Button.h"//advance notice of the agreement. The role of @class is the same as the @protocol buttondelegate; @interface buttonlisterner:nsobject<buttondelegate> @end
In the buttonlisterner.m file
#import "Buttonlisterner.h" #import "Button.h" @implementation buttonlisterner-(void) OnClick: (Button *) but{ NSLog (@ "OnClick ..."); @end
in the main.m
int main (int argc, const char * argv[]) { @autoreleasepool { button* button = [[button alloc]init]; buttonlisterner* listenter = [[Buttonlisterner alloc]init]; Button.delegate=listenter; [Button Click]; } return 0;}
Objective-c the Protocol