【发布时间】:2016-12-17 00:30:19
【问题描述】:
谁能解释一下为什么这不会泄漏?
我在closure 中捕获self,所以我会有两个相互指向的强指针,因此,永远不应为 Person 对象调用 deinit 消息。
首先,这是我的班级Person:
class Person {
var name: String
init(name: String) { self.name = name }
deinit { print("\(name) is being deinitialized") }
}
这是我的 ViewController 的实现:
class ViewController: UIViewController {
var john:Person?
func callClosureFunction( closure:(name:Bool) -> () ) {
closure(name: true)
}
override func viewDidLoad() {
super.viewDidLoad()
john = Person(name:"John")
self.callClosureFunction { (name) in
self.john?.name = "John Appleseed"
self.john = nil
// xcode prints - John Appleseed is being deinitialized
}
}
}
我希望能够通过以下方式解决问题:
self.callClosureFunction { [weak self] (name) in ...
但这甚至没有必要。为什么?
【问题讨论】:
标签: swift memory-leaks closures retain-cycle strong-references