簡體   English   中英

調用dequeueReusableCell(withIdentifier:for :) swift時內存泄漏

[英]Memory leaks when calls dequeueReusableCell(withIdentifier:for:) swift

我必須展示幾個不同的細胞。 我為此調用了tableView(_:cellForRowAt:) ,在方法中,我為UITableViceCell不同類使用了兩個不同的ID

這是一個簡單的代碼:

class SimpleView: UITableViewController {
...

let cellIdMain = "JournalMainCellID"
let cellIdExtra = "JournalMainSceneAddNewID"

...

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.row == journals.count {
        guard let cellAdding = tableView.dequeueReusableCell(withIdentifier: cellIdExtra, for: indexPath) as? JournalMainSceneAddNew else {
            fatalError("Cannot connect to the cell")
        }
        return cellAdding
    }

    guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdMain, for: indexPath) as? JournalMainSceneCell else {
        fatalError("Cannot connect to the cell")
    }
    cell.numberOfCountriesLabel.text = "\(journals[indexPath.row].numberOFCountries)"
    return cell
}
}

當我試圖找到內存泄漏時,我發現:

在此輸入圖像描述

當我點擊我發現的細節時:

在此輸入圖像描述

為什么會這樣? 它看起來非常簡單明了。

更新:圖片已更新。

如果條件僅在一種情況下作為indexpath.row的條件將只等於count,即使它不起作用,因為如果它將執行后如果它將執行代碼塊,如果這意味着你的if塊是浪費,為什么你在使用cell.delegate嗎?

使用以下代碼更新代碼。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.row == journals.count {

        let cellAdding: JournalMainSceneAddNew = {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdExtra) as? JournalMainSceneAddNew else {                
                return JournalMainSceneAddNew(style: UITableViewCellStyle.value1, reuseIdentifier: cellIdExtra)
            }
            return cell
        }()

        return cellAdding
    }

    let cell: JournalMainSceneCell = {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdMain) as? JournalMainSceneCell else {                
            return JournalMainSceneCell(style: UITableViewCellStyle.value1, reuseIdentifier: cellIdMain)
        }
        return cell
    }()

    cell.numberOfCountriesLabel.text = "\(journals[indexPath.row].numberOFCountries)"
    return cell
}

暫無
暫無

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

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