swift - 防止 Swift 函数指针中的保留循环

标签 swift automatic-ref-counting

在 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/

相关文章:

ios - 我对 ORKResultPredicate 的 predicateForConsent 函数有问题

swift - 每当我从菜单加载游戏场景时,尺寸就太大了

objective-c - 在dealloc中应该将什么样的属性设置为nil?

swift - Swift 4 中的 KVO 监听器问题

ios - 如何从解析数组中删除项目?

objective-c - 使用 ARC,静态常量数组的值是否自动分配为 nil?

cocoa-touch - NSOperation 由 NSOperationQueue 保留

ios - AVAudioPlayer 属于 ARC 类别

objective-c - -fno-objc-arc 无法禁用 ARC

json - 可选值的包装问题