存储为变量的 Swift 闭包会导致内存泄漏

Alb*_*cía 3 iphone memory-leaks ios retain-cycle swift

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

变量定义如下:

public class MyCell: UICollectionViewCell {
    public var callback: ((MyCell)->Void)?
}
Run Code Online (Sandbox Code Playgroud)

如果我使用委托而不是闭包,保留周期就会消失,但我想知道如何用闭包来定义它以备将来使用。

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

编辑

用法:

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

   // After dequeuing the cell:
   {
       cell.callback = onActionOccurs(_:)
   }
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Rei*_*ian 6

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

public class MyCell: UICollectionViewCell {
    public var callback: (()->Void)?
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用它,就像这个例子

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

   // After dequeuing the cell:
   {
       cell.callback = {
         cell.backgroundColor = .red // For example
        }
   }
}
Run Code Online (Sandbox Code Playgroud)

但是如果您需要使用 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 let self = self else { return }

         self.viewControllerMethod()
        }
   }
}
Run Code Online (Sandbox Code Playgroud)