Protocol in Objective-C

Source: Internet
Author: User

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;}



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.