快速调用 dequeueReusableCell(withIdentifier:for:) 时内存泄漏 [英] Memory leaks when calls dequeueReusableCell(withIdentifier:for:) swift

查看:82
本文介绍了快速调用 dequeueReusableCell(withIdentifier:for:) 时内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须展示几个不同的单元格.我为此调用了 tableView(_:cellForRowAt:),在该方法中,我为 UITableViceCell

I have to show a couple of different cells. I called tableView(_:cellForRowAt:) for that, and in the method I use two different IDs for different classes of UITableViceCell

这是一个简单的代码:

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
}
}

当我尝试查找内存泄漏时,我发现:

When I tried to find memory leaks I found:

当我点击我发现的详细信息时:

When I click on the details I found:

为什么会这样?它看起来非常简单明了.

Why this happened? It looks pretty simple and straightforward.

更新:图片已更新.

推荐答案

使用以下代码更新您的代码.

Update your code with the following code.

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
}

这篇关于快速调用 dequeueReusableCell(withIdentifier:for:) 时内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆