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 <Foundation/Foundation. h> // class declaration @ class button; // <> indicates implementing a protocol, nsobject is the underlying protocol // buttondelegate is the protocol name @ protocol buttondelegate <nsobject>-(void) onclick :( button *) But; @ end @ interface button: nsobject // nonatomic does not require multi-thread management. delegate is the 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 (@ "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 <Foundation/Foundation. h> # import "button. H "// declare the protocol in advance. The role of @ class is the same as that of @ 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 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;}