Protocol in objective-C

Source: Internet
Author: User

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



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.