打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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 <FirstProtocol, SecondProtocol>
-(void)third;
@end

#endif /* ThirdProtocol_h */

4)、DoProtocol.h

#import <Foundation/Foundation.h>
#import "ThirdProtocol.h"

#ifndef DoProtocol_h
#define DoProtocol_h
@interface DoProtocol : NSObject <ThirdProtocol>
@end

#endif /* DoProtocol_h */

5)、DoProtocol.m

#import <Foundation/Foundation.h>

#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<FirstProtocol> *first = [[DoProtocol alloc] init];
        [first first];
        
        id<SecondProtocol> second = [[DoProtocol alloc] init];
        [second second];
    }
}


4、运行结果

this first method
this second method
this third method
this first method
this second method
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
#ifdef 如何实现“与或”
禁止NSLog使用,在release版本禁止输出NSLog内容
#ifndef
#pragma once 和 #ifndef #define …#endif 有什么不同?
#ifndef/#define/#endif使用详解
VS2010编译错误:fatal error C1189: #error : This file requires _WIN32_WINNT to be #defined at least to 0x
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服