美文网首页
Protocol协议

Protocol协议

作者: SimpleSJ | 来源:发表于2018-11-22 14:00 被阅读0次

    1.@required和@optional关键字

    • @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
    

    相关文章

      网友评论

          本文标题:Protocol协议

          本文链接:https://www.haomeiwen.com/subject/azakqqtx.html