博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Protocol入门
阅读量:4685 次
发布时间:2019-06-09

本文共 1653 字,大约阅读时间需要 5 分钟。

参考:

介绍:

     Protocol在iOS中就是协议,简单的理解就是一组函数的集合,这个集合中有分为必需实现的和可选实现的。一般来说,protocol会与delegate模式一同使用。说白了,一个protocol就是一组实现规范。

定义:

@protocol testProtocol   // 协议名称@required                   // 必需实现的方法-(void)getTheResult;@optional                   // 可选实现的方法-(void)running;@end

使用:

@interface GameProtocol : NSObject@property id
delegate; // 代理设置-(void)runTheGame;@end@implementation GameProtocol-(instancetype)init{ self = [super init]; [self addObserver:self forKeyPath:@"delegate" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:@""]; return self;} -(void)dealloc{ if (self) { [self removeObserver:self forKeyPath:@"delegate"]; //要移除KVO,否则会出错 }} -(void)runTheGame{ [self.delegate getTheResult];} -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ if ([keyPath isEqualToString:@"delegate"]) { [self runTheGame]; }}@end

 

结合委托模式:

@interface ProtocolViewController ()
@end@implementation ProtocolViewController #param mark - testProtocol协议-(void)getTheResult{ NSLog(@"%@",@"get the result");}- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. GameProtocol *game = [[GameProtocol alloc]init]; game.delegate = self; [game runTheGame];}

输出结果:

2015-01-15 20:44:58.195 testDemo[10476:2067475] get the result2015-01-15 20:44:58.196 testDemo[10476:2067475] get the result

 

总结:

     协议就是一组规范,是对一组方法的封装,其他对象调用的时候,只需设置这个代理,然后在该对象中直接调用,这样的话这个对象就能很好的封装,具体的协议实现在调用这个对象的时候再具体实现,这样就能够做到逻辑的封装,与业务逻辑无关。

转载于:https://www.cnblogs.com/starwolf/p/4227227.html

你可能感兴趣的文章
IIS的ISAPI接口简介
查看>>
python:open/文件操作
查看>>
16 乘法口诀输出
查看>>
mac 常用地址
查看>>
鼠标经过切换图片
查看>>
流程控制 Day06
查看>>
Linux下安装Tomcat
查看>>
windows live writer 2012 0x80070643
查看>>
C程序的启动和终止
查看>>
asp.net web 定时执行任务
查看>>
tomcat 和MySQL的安装
查看>>
11.5 内部类
查看>>
Cosine Similarity
查看>>
浅谈JAVA集合框架
查看>>
halt和shutdown 的区别
查看>>
git常用操作
查看>>
京东SSO单点登陆实现分析
查看>>
render()方法是render_to_response
查看>>
u-boot启动第一阶段
查看>>
谢惠民,恽自求,易法槐,钱定边编数学分析习题课讲义23.2.3练习题参考解答[来自陶哲轩小弟]...
查看>>