问题
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
Here is a simple code:
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.
Updated: pictures were updated.
回答1:
you are writing if conditions which will work only in one case as indexpath.row will only be equal to count even though it will not work because after going through if it will execute block of code after if which means your if block is waste and why are you using cell.delegate??
回答2:
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
}
来源:https://stackoverflow.com/questions/55501778/memory-leaks-when-calls-dequeuereusablecellwithidentifierfor-swift