委托通常是符合协议的匿名对象。
协议和委托
协议和代表是两个相关但不同的概念:
协议是一个类可以遵循的接口,这意味着类实现了列出的方法。
被称为委托的 Delegate 应用程序是一种设计模式。
在一端,我们有继承的概念,它在子类和它的超类之间创建了一个紧密耦合,而 Delegation 设计模式提供了一个替代方案来避免这种紧密耦合,使用它我们可以基于匿名 Delegate 对象创建一个更松散的关系。
比如你有两个View 视图 ViewA
和 ViewB
示例B 创建于B之内
于是A可以发送消息给B实例
但是如果要反向通讯,我们就要实现委托
(所以使用委托,B的实例可以发送消息给A实例)
下面是实现委托的步骤
-
B实例里创建协议:
@protocol ViewBDelegate -(void) exampleDelegateMethod; @end
-
定义委托于发送方的class里面
@interface ViewB : UIView @property (nonatomic, weak) id< ViewBDelegate > delegate; @end
-
在ViewA 类里获取协议
@interfac ViewA: UIView < ViewBDelegate >
-
设置委托
-(void) anyFunction { // create Class ViewB's instance and set the delegate [viewB setDelegate:self]; }
-
在
ViewA 实现委托
-(void) exampleDelegateMethod { // will be called by Class ViewB's instance }
-
用
ViewB
的方法调用委托的方法-(void) callDelegateMethod { [delegate exampleDelegateMethod]; //assuming the delegate is assigned otherwise error }
分类: 默认 标签: 发布于: 2021-12-02 17:35:57, 更新于: 2021-12-02 17:57:21