IOS之学习笔记十四(协议的定义和实现)

1、正式协议的定义

@protocol 协议名 <父协议1, 父协议2>

{

    零个到多个方法定义

}

一个协议可以有多个直接父协议,但协议只能继承协议,不能继承类

协议只有方法签名,没有方法实现









2、实现协议

@interface 类名 : 父类 <协议1,协议2…>

@end

协议和java里面的接口差不多

如果要使用协议定义变量,有如下两种语法

NSObject<协议1,协议2>*变量;

id<协议1,协议2> 变量;


@optional关键字之后声明的方法可选实现

@required关键字之后声明的方法必选实现






3、测试Demo

1)、FirstProtocol.h

#ifndef FirstProtocol_h
#define FirstProtocol_h

@protocol FirstProtocol
-(void)first;
@end

#endif /* FirstProtocol_h */


2)、SecondProtocol.h

#ifndef SecondProtocol_h
#define SecondProtocol_h
@protocol SecondProtocol
-(void)second;
@end

#endif /* SecondProtocol_h */



3)、ThirdProtocol.h

#import "FirstProtocol.h"
#import "SecondProtocol.h"

#ifndef ThirdProtocol_h
#define ThirdProtocol_h
@protocol ThirdProtocol 
-(void)third;
@end

#endif /* ThirdProtocol_h */


4)、DoProtocol.h

#import 
#import "ThirdProtocol.h"

#ifndef DoProtocol_h
#define DoProtocol_h
@interface DoProtocol : NSObject 
@end

#endif /* DoProtocol_h */



5)、DoProtocol.m

#import 

#import "DoProtocol.h"

@implementation DoProtocol
-(void)first
{
    NSLog(@"this first method");
}
-(void)second
{
    NSLog(@"this second method");
}
-(void)third
{
    NSLog(@"this third method");
}
@end


6)、main.m

#import "DoProtocol.h"
#import "ThirdProtocol.h"
#import "FirstProtocol.h"

int main(int argc, char * argv[]) {
    @autoreleasepool {
        DoProtocol *protocal = [DoProtocol new];
        [protocal first];
        [protocal second];
        [protocal third];
        
        NSObject *first = [[DoProtocol alloc] init];
        [first first];
        
        id second = [[DoProtocol alloc] init];
        [second second];
    }
}



4、运行结果

this first method
this second method
this third method
this first method
this second method


你可能感兴趣的:(IOS之学习笔记十四(协议的定义和实现))