oc - 协议 protocol

@protocol myProtocol <NSObject> // 基协议

 

@required // 声明了必须要实现的,默认情况下都是          

@required

- (void)walk;

- (void)speak;

- (void)think; // think在类实现中未实现会警告!!!

@optional

- (void)sing;

- (void)laugh;

 

@end

协议可以声明一大堆方法,但不能声明成员变量;

两个协议之间不能继承,但协议可以遵守另一个协议;

子类可以遵守父类遵守的协议;

 

NSObject<myProtocol,allProtocol> * stu = [[Student alloc]init];

等价于

Student *stu = [[Student alloc]init];// 任何类

 

   [stu eat]; // 子类重写了,调用子类的

   [stu run]; // 子类没重写,向上找找到父类的方法

 

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;

若报错,就检验出stu没遵守协议

 

 

 

 

 

#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

posted on 2015-04-08 22:54  杰瑞-张鑫  阅读(123)  评论(0)    收藏  举报