从未调用过UITableViewCell对象deinit

erv*_*nux 6 memory-management uitableview swift deinit

问题出在我的项目中。但是我也在新的xcode草案项目中尝试了Master-Detail Application。

我创建了基本Cell类,并将该单元映射到情节提要上。删除操作后,不会调用deinit。没有关于单元格的强项或弱项。

class Cell:UITableViewCell {
    deinit{
        print("Deinit Called")
    }
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! Cell

    let object = objects[indexPath.row] as! NSDate
    cell.textLabel!.text = object.description
    return cell
}
Run Code Online (Sandbox Code Playgroud)

Rod*_*ici 7

UITableViewCells 作为一个惰性变量工作,它们在第一次使用时被初始化并且只要初始化它们的 UITableView 处于活动状态就会保持活动状态,这发生在 register:forIdentifier: 被调用的那一刻。如果您使用的是为您完成的故事板。

为什么完成了?每个单元格都可以使用 dequeueReusableCellWithIdentifier 重新利用,因此 UITableView 保持一个实例处于活动状态,以便在需要时使用。

如果你需要清理一些数据,只需在 UITableViewCell 上调用 prepareForReuse

  • @P5ycH0 从 iOS 9 开始,不再需要删除 deinit 中的观察者。请参阅此处的讨论部分:https://developer.apple.com/documentation/foundation/notificationcenter/1407263-removeobserver。但是如上所述,您可能希望停止在 prepareForReuse 中收听并在 cellForRowAt 中重新开始。 (2认同)