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];
}
 
 
 
 
posted @ 2015-10-20 14:10  Santiago_1991  阅读(550)  评论(0编辑  收藏  举报