防止Swift函数指针中的retain循环

防止Swift函数指针中的retain循环,swift,automatic-ref-counting,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

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

}
还有一个像这样的视图控制器,它具有(并且想要)对该对象的强引用

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"

    }
}
放弃视图控制器时,数据源不会被释放,视图控制器也不会被释放,因为它持有对视图控制器上的
decorateAtthing
函数的强引用

通过在
ViewController
中执行此操作,您可以停止此循环并让装饰器释放,但它感觉很凌乱

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
     datasource?.decorator = nil
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    datasource?.decorator = decorateThatThing
}
因此,问题是如何声明变量和/或函数,以避免必须手动拆卸数据源,从而在放弃视图控制器时,也会释放关联的数据源。

而不是

datasource.decorator = decorateThatThing
你可以用

datasource.decorator = { [unowned self] cell in
    self.decorateThatThing(cell)
}

不起作用。我希望视图控制器拥有数据源。如果在调用
decorator
时解除分配了
self
,则在实例化fyi时使用
unowned
丢弃它将导致崩溃。您也可以在.Yep中使用
weak
,如果调用
decorator
时有可能释放
self
,那么一定要使用
weak
。但如果不可能,则使用
无主
。使用
weak
并不昂贵,但也不是免费的。