繁体   English   中英

存储为变量的Swift闭包会产生内存泄漏

[英]Swift closure stored as a variable produces memory leak

将闭包定义为变量时,我有一个保留周期。

变量定义如下:

public class MyCell: UICollectionViewCell {
    public var callback: ((MyCell)->Void)?
}

如果我使用委托而不是闭包,保留周期会消失,但我想知道如何使用闭包来定义未来的情况。

我试图将回调变量设置为weak ,但是,正如我想的那样,weak属性只能应用于类和类绑定协议类型。

编辑

用法:

class CustomController: UIViewController {
   private func onActionOccurs(_ cell: MyCell) {
       cell.backgroundColor = .red // For example
   }

   // After dequeuing the cell:
   {
       cell.callback = onActionOccurs(_:)
   }
}

谢谢

如果您不需要使用self,那么您可以使用单元格本身,并在单元格中修改闭包实现

public class MyCell: UICollectionViewCell {
    public var callback: (()->Void)?
}

那么你可以使用它,就像这个例子

class CustomController: UIViewController {
   private func onActionOccurs(_ cell: MyCell) {
       cell.backgroundColor = .red // For example
   }

   // After dequeuing the cell:
   {
       cell.callback = {
         cell.backgroundColor = .red // For example
        }
   }
}

但是如果你需要使用ViewController方法那么你需要使用[weak self]捕获列表如果你需要使用UIViewController方法

class CustomController: UIViewController {
   private func onActionOccurs(_ cell: MyCell) {
       cell.backgroundColor = .red // For example
   }

   // After dequeuing the cell:
   {
       cell.callback = { [weak self] in
         guard self != nil else {
            return
         }

         self!.viewControllerMethod()
        }
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM