3

我已经知道我的问题的解决方案,但我真的不明白这里发生了什么。我有一个UITableViewController将单元格放入didSelectRow并将其用于其他功能的东西。我将单元格作为AnyObject?. 现在,当我深入了解详细 VC 然后再次备份时,再重复这些步骤 2 次,我的应用程序崩溃了。

首先,我认为这是我的应用程序中其他地方的问题,但后来我创建了一个示例项目,除了那几行之外什么都没有,并设法重现了这个错误。我也已经提交了雷达,但我不想死掉(因为你永远不会从那些雷达人那里听到回音);)有人可以向我解释这里发生了什么!

final class MasterViewController: UITableViewController {

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let cell = tableView.cellForRow(at: indexPath)
        doSomethingWith(sender: cell)
    }

}

extension MasterViewController {
    func doSomethingWith(sender: AnyObject?) {
        // I don't even use that sender!!!
        // If the function would read    doSomethingWith(sender: Any?)     everything would be ok!
    }
}

如果您愿意,可以在以下网址下载整个示例:http ://www.georgbachmann.com/demo/CrashTest.zip

我真的很想知道 swift 编译器在那里做什么!

::编辑::

我刚刚注意到崩溃还取决于doSomethingWith:是否处于扩展中!

4

1 回答 1

0

基本上,您不会“拥有”可重复使用的单元格。拥有UITableView它们。由于您将同一个单元格三次传递给具有强引用的函数(您写过,您知道解决方案,所以我省略了它),您增加了单元格的引用计数(在本例中为 +3,但没关系)。在某些时候UITableView决定释放它的细胞,但你UIViewController对它们有很强的参考。此时应用程序崩溃。这里没有错误 - 你不应该传递你不拥有的对象。

于 2016-09-21T15:26:04.650 回答