Protocol in Objective-C
Protocol in Objective-C
Protocol
In short, it is a list of methods. The declared methods can be implemented by any class. This mode is generally called the (delegation) mode.
In iOS and OS X, Apple uses a large number of proxy modes to implement View (UI control) and Controller (Controller) in MVC)
The following is an example.
Declare a Button class and a Buttonlisterner class
In the Button. h file
# Import
// Class declaration @ class Button; // <> indicates implementing a protocol. NSObject is the underlying protocol. // ButtonDelegate is the protocol name @ protocol ButtonDelegate
-(Void) onClick :( Button *) but; @ end @ interface Button: NSObject // nonatomic does not require multi-thread management. delegate is the Button listener @ property (nonatomic, retain) id
Delegate;-(void) Click; @ end
In the Button. m file
# Import "Button. h "@ implementation Button //-(void) dealloc {// [super dealloc]; //}-(void) click {NSLog (@ "Click button is clicked... "); // If there is an onClick: method, call this method if ([_ delegate respondsToSelector: @ selector (onClick :)]) {// and tell the listener which button has been clicked [_ delegate onClick: self];} @ end
In the Buttonlisterner. h file
# Import
# Import "Button. h" // declare the protocol in advance. The role of @ class is the same as that of @ protocol ButtonDelegate; @ interface Buttonlisterner: NSObject
@ End
In the Buttonlisterner. m file
#import "Buttonlisterner.h"#import "Button.h"@implementation Buttonlisterner-(void)onClick:(Button *)but{ NSLog(@"onClick...");}@end
In 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;}