@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