Tru*_*an1 1 ios automatic-ref-counting strong-references swift
对于NSNotificationCenter块,我必须使用[unown self]避免强引用周期:
NSNotificationCenter.defaultCenter()
.addObserverForName(UIApplicationWillEnterForegroundNotification,
object: nil,
queue: nil,
usingBlock: { [unowned self] (notification : NSNotification!) -> Void in
self.add(123)
})
Run Code Online (Sandbox Code Playgroud)
但是,在UIView.animateWithDuration中,我不必使用[unown self]:
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.someOutlet.alpha = 1.0
self.someMethod()
})
Run Code Online (Sandbox Code Playgroud)
有什么不同?
动画块和通知中心块之间的唯一区别是,动画块的生存期非常短-立即执行然后释放。
在这两种情况下,块都会捕获self;但是只有NSNotificationCenter代码是有问题的,因为通知中心可以随时发生,因此通知中心将无限期持有对该块的引用。
请注意,这与循环引用不同。循环引用通常由持有对捕获自身的块的引用的对象创建,如下所示:
self.myBlock = {
self.doSomething()
}
Run Code Online (Sandbox Code Playgroud)
该循环引用意味着self将永远不会被释放。通知中心不是循环引用(因为self不保存对通知中心的引用),它只是一个常规引用,将被保留直到观察者被移除为止。
| 归档时间: |
|
| 查看次数: |
854 次 |
| 最近记录: |