Protocol协议

1.@required和@optional关键字

  • @required:这个方法必须要实现
  • @optional:这个方法不一定要实现
#import 

@protocol CommonProtocol 

@required
-(void)eat;
-(void)sleep;

@optional
-(void)play;

@end

2.只要父类遵守了某个协议,那么子类也遵守

Animal.h
#import 
#import "CommonProtocol.h"
@interface Animal : NSObject
@property(weak,nonatomic)iddelegate;
@end

Animal.m
#import "Animal.h"
@implementation Animal
-(void)eat{
    if ([self.delegate respondsToSelector:@selector(eat)]) {
        [self.delegate eat];
    }
}
-(void)sleep{
    if ([self.delegate respondsToSelector:@selector(sleep)]) {
        [self.delegate sleep];
    }
}
-(void)play{
    if ([self.delegate respondsToSelector:@selector(play)]) {
        [self.delegate play];
    }
}
@end

Dog.h
@interface Dog : Animal
@end

Dog.m
@implementation Dog
-(void)eat{
    NSLog(@"%s",__func__);
}
@end

3.OC不能继承多个类(单继承)但是能够遵守多个协议

#import "SportProtocol.h"
#import "StudyProtocol.h"

@interface Student : NSObject 

@end

4.协议可以遵守协议,一个协议遵守了另一个协议,就可以拥有另一份协议中的方法声明

@protocol A
-(void)methodA;
@end

@protocol B 
-(void)methodB;
@end
@interface Student : NSObject 
-(void)methodA; // 同时拥有A/B协议中的方法声明
-(void)methodB;
@end

你可能感兴趣的:(Protocol协议)