当前位置:网站首页>OC-协议
OC-协议
2022-08-04 21:37:00 【彭同学她同桌】
什么是协议
定义一组方法 由其他类来实现。
如果一个类实现了这个协议则代表这个类遵循了这个协议
格式
@protocol 协议的名字<父协议> // 一般情况下 父协议是NSObject
创建协议
//Pro.h
@protocol pro<NSObject>
-(void)play;//并不在Son的头文件中声明 而是在协议中声明这个方法
@optional//标识下面这个函数可实现 也可以不实现
-(void)read;
@required//标识下面这个函数必须实现 默认就是required
-(void)eat;
@end
导入协议
//Son.h
import"Pro.h"
@interface Son:NSObject<pro/*,这里可以添加其他的协议*/>
//-(void)play//不声明
@end
//Son.m
import"Son.h"
@implementation Son
-(void)play
{
NSLog(@"%@",__func__)
}
@end
//main.m
import"Foundation/Foundation.h"
import"Son.h"
int main()
{
Son *s = [[Son alloc]init];
[s play];//发现也能调用
}
协议限制传入的参数 也可以限制成员变量
创建协议
//people.h 创建一个人的协议
@protocol people<NSObject>
-(char*)name;
-(id)initWithName;
@end
创建女人类
//Woman.h
import"people.h"
@interface Woman:NSObject<people>
{
char *_name;
id friend;//可以改成下面这样
}
//@property id<people>friend;//直接限制成员变量
-(void)setWithFriend:(id)<people>f
@end
//Woman.m
import"Woman.h"
@implementation Woman
-(void)setWithFriend:(id)<people>f//只允许与遵守人协议的对象做朋友
{
NSLog(@"%@:%@",__func__,[f name]);
}
-(id)initWithName:(char*)n;
{
if((self = [[super alloc]init])!= nil)
{
_name = n;
}
return self;
}
-(char*)name
{
return name;
}
@end
创建男人类
//Man.h
import"people.h"
@interface Man:NSObject<people>
{
char *_name;
id *friend;
}
@end
//Man.m
import"Man.h"
@implementation Man
-(id)initWithName:(char*)n;
{
if((self = [[super alloc]init])!= nil)
{
_name = n;
}
return self;
}
-(char*)name
{
return name;
}
@end
创建狗类
//Dog.h
@interface Dog:NSObject
@end
//Dog.m
import"Dog.h"
@implementation Dog
@end
main
int main()
{
Woman *hong = [[Woman alloc]initWithName:@"小红"];
Man*ming = [[Man alloc]initWithName:@"小明"];
Dog*huang = [[Dog alloc]init];
[hong setWithFriend:ming];//setWithFriend:小明
//[hong setWithFriend:huang];//这样就会报错 因为dog不遵守人的协议
}
BOOL conformsToProtocol: 判断是否遵循协议
[hong conformsToProtocol:@protocol(people)];
边栏推荐
猜你喜欢

Domestic PMP certificate of gold content how

buu web

Qiangwang Cup 2022 - WEB

动手学深度学习_NiN

DSPE-PEG-Aldehyde, DSPE-PEG-CHO, Phospholipid-Polyethylene Glycol-Aldehyde A hydrophobic 18-carbon phospholipid

ES6高级-async的用法

PMP证书在哪些行业有用?

STM32MP157A驱动开发 | 01- 板载LED作为系统心跳指示灯

unity2D横版游戏教程8-音效

laravel whereDoesntHave
随机推荐
boostrap多选PID查找端口 window
【ubuntu20.04安装MySQL以及MySQL-workbench可视化工具】
Altium Designer 19.1.18 - 画多边形铜皮挖空时,针对光标胡乱捕获的解决方法
数电快速入门(一)(BCD码和三种基本逻辑运算的介绍)
可视化工作流引擎开发OA系统,让企业少花冤枉钱
LayaBox---TypeScript---首次接触遇到的问题
PyTorch Geometric (PyG) 安装教程
Driving point cloud format changes bring efficiency improvement
Zynq Fpga图像处理之AXI接口应用——axi_lite接口使用
Axure9基本交互操作(一)
openresty lua-resty-template页面静态化
【PCBA方案设计】握力计方案
buu web
【线性代数03】消元法展示以及AX=b的4种解情况
1319_STM32F103串口BootLoader移植
【PCBA program design】Grip dynamometer program
Codeforces Round #811 (Div. 3)
LayaBox---TypeScript---Problems encountered at first contact
ROS播包可视化
DGL安装教程