Ios为我所用

@protocol myProtocol <NSObject> // 基协议

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

@required

– (void)walk;

– (void)speak;

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

@optional

– (void)sing;

– (void)laugh;

@end

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

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

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

NSObject<myProtocol,allProtocol> * stu = [[Student

等价于

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{

@"student can exam.");

}

– (void)eat{

@"student can eat");

}

@end

#import <Foundation/Foundation.h>

@protocol allProtocol <NSObject>

– (void)eat;

– (void)run;

@end

#import "Person.h"

@implementation Person

– (void)eat{

@"person can eat");

}

– (void)run{

@"person can run");

}

@end

风景如何,其实并不重要。重要的是,你在我的身边。

Ios为我所用

相关文章:

你感兴趣的文章:

标签云: