码迷,mamicode.com
首页 > 其他好文 > 详细

oc - 协议 protocol

时间:2015-04-09 00:41:16      阅读:207      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!