IOS的三种CallBack

之前一直对callback很困惑,现在稍微有点头绪:

不妨理解为,I call you, and you call me back.
 
三种模式的概念
1.Target-action模式
 
 
这里的timer对象调用的updateLastTime:就是一个callback function,当然如果吧target设为self让后seletor的函数是自己的函数更容易理解,一个对象一个函数。
 
2.Helper或者delegate
举个例子:我是A,我生成并初始化一个对象B,B有个delegate,我初始化的时候把他的delegate指定为我自己,然后B在某个条件下通过delegate来调用了由我实现的代理函数,B call me back with the delegate functions,一个对象多个函数。
 
3.Notification
理解了前面两个Notification就比较好理解了,同样从callback的角度来理解,我是A我持有并生成一个对象,然后我调用defaultCenter对象的增加观察者函数,但是我传给他的是我声明的对象的函数,我调用了它(指defaultcenter)的函数,当某一事件发生时,他会回过头来调用我给它的对象的函数。
 
三种模式的适用情况
For callbacks: When sending one callback to one object, Apple uses target-action. 
 
When sending an assortment of callbacks to one object, Apple uses a helper object with a protocol. These helper objects are typically called delegates or data sources. 
 
Objects that might need to trigger callbacks in several other objects (like NSTimeZone) use notifications.
 
三种模式使用时的持有关系(object ownership )
三种模式使用的时候都有strong reference cycle的风险。
1.Target-action
Objects do not own their targets. If you create an object that is a target, your object should zero the target pointer in its dealloc method:
- (void)dealloc
{
    [buttonThatKeepsSendingMeMessages setTarget:nil];
}
 
2.Helper
Objects do not own their delegates or data sources. If you create an object that is a delegate or data source, your object should“excuse” itself in its dealloc method:
- (void)dealloc
{
    [windowThatBossesMeAround setDelegate:nil];
    [tableViewThatBegsForData setDataSource:nil];
}
 
3.Notification
 Notification centers do not own their observers. If an object is an observer, it will typically remove itself from the notification center in its dealloc method:
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
 
 
 
 

转载于:https://www.cnblogs.com/simpleisgood/p/4894656.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值