Protocol协议

2018-11-22  本文已影响0人  SimpleSJ

1.@required和@optional关键字

#import <Foundation/Foundation.h>

@protocol CommonProtocol <NSObject>

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

@optional
-(void)play;

@end

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

Animal.h
#import <Foundation/Foundation.h>
#import "CommonProtocol.h"
@interface Animal : NSObject<CommonProtocol>
@property(weak,nonatomic)id<CommonProtocol>delegate;
@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 <SportProtocol, StudyProtocol>

@end

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

@protocol A
-(void)methodA;
@end

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

猜你喜欢

热点阅读