Objective-C中的protocol用法

来源:互联网 发布:java基础入门课后笔记 编辑:程序博客网 时间:2024/06/05 02:45

//接口中声明引用的协议

#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;
}