OC中代理设计模式

什么是代理设计模式

在开发中往往会遇到这几种情景,可以使用代理模式处理:
1.当A对象想监听B对象的一些变化时。
2. 当B对象发生一些事情, 想通知A对象的时候。
3.当对象A无法处理某些行为的时候,想让对象B帮忙处理(让对象B成为对象A的代理对象。

代理解决对象之间传值

  • 找代理三个步骤
    1.列出自己不想做或者不能做的事情,制定一个协议,例如买房子需求(@protocol PersonProtocol <NSObject >)
    2.定一个代理属性(weak修饰防止循环引用)
    @property (nonatomic, weak) id<PersonProtocol> delegate;
    3.当自己触发某个事件,就让代理去执行协议方法
    [self.delegate personFindHourse:self];

    招代理的类对应的.h文件代码

    #import <Foundation/Foundation.h>
    @class Person;
    @protocol PersonProtocol <NSObject>
    - (void)personFindHourse:(Person *)person;
    @end
    
    @interface Person : NSObject
    @property (nonatomic, strong) id<PersonProtocol> delegate;
    - (void)findHourse;
    @end
    

    招代理的类对应的.m文件代码

    #import "Person.h"
    @implementation Person
    - (void)findHourse
    {
     if ([self.delegate respondsToSelector:@selector(personFindHourse:)]) {
         [self.delegate personFindHourse:self];
     }
     }
     @end
    
    
  • 做代理遵守的规则

    1.遵守代理协议

    @interface LinkHome : NSObject <PersonProtocol>

    #import <Foundation/Foundation.h>
    @protocol PersonProtocol;
    @interface LinkHome : NSObject <PersonProtocol>
    @end
    

    2.实现代理方法

    #import "LinkHome.h"
    #import "Person.h"
    @implementation LinkHome
    - (void)personFindHourse:(Person *)person
    {
     NSLog(@"%s", __func__);
     }
     @end
    

    3.建立两者联系,找代理的类给代理赋值

     Person *p = [Person new];
     LinkHome *linkhome = [LinkHome new];
     //链家实现了找房协议的方法,所以让链家成为人的代理
     p.delegate = linkhome;
     //人只要调用findHourse方法,代理就会帮人去找房
     [p findHourse];
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值