//接口中声明引用的协议,协议只是接口的声明,所以没有实现m文件,只有h类文件
//实现多个协议,类似java实现多个接口
#import <Foundation/Foundation.h>
@protocol Study;
@protocol Learn;
@interface Student : NSObject<Study, Learn>
@end
//实体类中导入协议
#import "Student.h"
#import "Study.h"
#import "Learn.h"
@implementation Student
- (void) test{
}
@end
//创建协议
#import <Foundation/Foundation.h>
@protocol Study <NSObject>
//default required
- (void) test3;
//必须实现的方法
//虽然字面上说必须实现,但是编译器并不强求某个类进行实现(编译器弱语法,不提示错误)
@required
- (void) test;
- (void) test1;
//@optional 表示可以实现,也可以不实现
@optional
- (void) test2;
@end
#import <Foundation/Foundation.h>
@protocol Learn <NSObject>
@end
main方法:
#import <Foundation/Foundation.h>
#import "Student.h"
@protocol Study;
int main(int argc, const char * argv[])
{
@autoreleasepool {
Student * stu = [[[Student alloc] init ] autorelease];
//判断是否遵守了某个协议
if([stu conformsToProtocol:@protocol(Study)]){
NSLog(@"Student follow protocol");
}
//有没有实现某个方法
if([stu respondsToSelector:@selector(test)]){
NSLog(@"Student do implement method ");
}
}
return 0;
}