在 Swift 中将函数作为对象传递时如何防止保留循环
假设您有一个像这样的数据源对象
import UIKit
class MagicDataSource:NSObject,UITableViewDatasource {
deinit {
println("bye mds")
}
//cant use unowned or weak here
var decorator:((cell:CustomCell)->Void)?
func tableView(tableView:UITableView,cellForRowAtIndexPath indexPath:NSIndexPath)->UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) as CustomCell
decorator?(cell)
return cell
}
}
像这样的 View Controller 具有(并且想要)对该对象的强引用
import UIKit
class ViewController: UIViewController {
var datasource:MagicDataSource? = MagicDataSource()
deinit {
println("bye ViewCon")
}
override func viewDidLoad() {
super.viewDidLoad()
datasource?.decorator = decorateThatThing
}
func decorateThatThing(cell:CustomCell) {
//neither of these two are valid
//[unowned self] (cell:CustomCell) in
//[weak self] (cell:CustomCell) in
cell.theLabel.text = "woot"
}
}
当您丢弃 View Controller 时,数据源将不会被释放, View Controller 也不会被释放,因为它持有对 View Controller 上的 decorateThatThing
函数的强引用。
您可以通过在 ViewController
中执行此操作来停止循环并释放装饰器,但感觉很困惑
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
datasource?.decorator = nil
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
datasource?.decorator = decorateThatThing
}
所以问题是我如何声明变量和/或函数以避免手动拆卸数据源,以便当 View Controller 被丢弃时关联的数据源也被释放。
最佳答案
而不是
datasource.decorator = decorateThatThing
你可以使用
datasource.decorator = { [unowned self] cell in
self.decorateThatThing(cell)
}
关于swift - 防止 Swift 函数指针中的保留循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28137993/