簡體   English   中英

如果 RxDataSource function 中的弱自我為零,如何正確返回帶有重用標識符的 CollectionViewCell?

[英]How do I properly return a CollectionViewCell with reuseIdentifier if weak self is nil in RxDataSource function?

我有一個問題,由於 memory 泄漏,數據源 function 用於使用 RxDataSource 的 CollectionView 中的 [unowned self] 更改為 [weak self]。 我現在收到了返回一個沒有reuseIdentifier 的空白collectionViewCell 的崩潰。 我知道我需要返回一個帶有重用 ID 的單元格。

建議進行哪些更改以正確處理此問題?

有人建議在 viewDidLoad() 中設置 collectionView.dataSource = nil 可以解決這個問題......

我在想而不是在'guard'檢查中返回CanvasItemCollectionViewCell(),我返回collectionView.dequeueReusableCell(for:indexPath,cellType:CanvasItemCollectionViewCell.self),但是如果self = self失敗,這不意味着collectionView是垃圾嗎?

這是一個難以調試的問題,因為這種崩潰不會始終如一地發生。

這里有一些截圖來描繪我正在看的東西。

RxData源代碼:

func dataSource()
        -> RxCollectionViewSectionedAnimatedDataSource<CanvasSectionModel> {
        RxCollectionViewSectionedAnimatedDataSource<CanvasSectionModel>(
            animationConfiguration: AnimationConfiguration(
                insertAnimation: .fade,
                reloadAnimation: .fade,
                deleteAnimation: .fade
            ),
            configureCell: { [weak self] dataSource, collectionView, indexPath, _ in
                guard let self = self else { return CanvasItemCollectionViewCell() }
                
                switch dataSource[indexPath] {
                case let .CellModel(model):
                    let cell = collectionView
                        .dequeueReusableCell(
                            for: indexPath,
                            cellType: CanvasItemCollectionViewCell.self
                        )

                    cell.model = model

                    cell.onDeleteHandler = { _ in
                        self.presentDeleteConfirmation { deleteConfirmed in
                            guard deleteConfirmed else { return }
                            self.viewModel.inputs.deletePage(withProofID: model.id)
                        }
                    }

                    return cell
                }
            }

崩潰

在此處輸入圖像描述

最終,問題出在這里:

cell.onDeleteHandler = { _ in
    self.presentDeleteConfirmation { deleteConfirmed in
        guard deleteConfirmed else { return }
        self.viewModel.inputs.deletePage(withProofID: model.id)
    }
}

不要使用self並且你不會有 self 引用的問題,所以你不需要導入一個弱的 self 然后擔心守衛讓 self ...

  • 對於第一個self引用,將其替換為UIViewController.top() (參見下文以了解實現。)
  • 對於第二個self引用,請改為捕獲viewModel
extension UIViewController {
    static func top() -> UIViewController {
        guard let rootViewController = UIApplication.shared.delegate?.window??.rootViewController else { fatalError("No view controller present in app?") }
        var result = rootViewController
        while let vc = result.presentedViewController, !vc.isBeingDismissed {
            result = vc
        }
        return result
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM