Objective-c the Protocol

Source: Internet
Author: User

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

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.