OC-Protocol Protocol

Source: Internet
Author: User

@protocol MyProtocol <NSObject>//Base agreement

@required//Declares what must be done, by default

@required

-(void) walk;

-(void) speak;

-(void) think; Think is not implemented in the class implementation warns!!!

@optional

-(void) sing;

-(void) laugh;

@end

A protocol can declare a large stack of methods, but cannot declare member variables;

Two agreements can not inherit, but the agreement may abide by another agreement;

Subclasses can abide by the agreement of the parent class;

nsobject<myprotocol,allprotocol> * stu = [[Student alloc]init];

Equivalent to

Student *stu = [[Student alloc]init];//any class

[Stu Eat]; Subclass overrides, calling the subclass's

[Stu Run]; Subclass not rewritten, find method of parent class up

Student can Eat

Person can run

Program ended with exit code:0

Student * stu = [[Student alloc]init];

Student <myProtocol> * Student = stu;

nsobject<myprotocol> * student = Stu;

id<myprotocol> student = Stu;

If an error is detected, the STU is not complying with the agreement.

#import "Student.h"

@implementation Student

-(void) exam{

NSLog (@ "Student can exam.");

}

-(void) eat{

NSLog (@ "Student can Eat");

}

@end

#import <Foundation/Foundation.h>

@protocol Allprotocol <NSObject>

-(void) eat;

-(void) run;

@end

#import "Person.h"

@implementation person

-(void) eat{

NSLog (@ "person can eat");

}

-(void) run{

NSLog (@ "person can run");

}

@end

OC-Protocol 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.