[英]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.