首页 > 其他 > 详细

oc - 协议 protocol

时间:2015-04-09 00:38:37      阅读:200      评论:0      收藏:0      [点我收藏+]

@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

oc - 协议 protocol

原文:http://www.cnblogs.com/qq343351666/p/4404864.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!