简体   繁体   English

如果UITableViewController在performBatchUpdates完成处理程序中捕获自身,这会导致保留周期吗?

[英]If a UITableViewController captures self in a performBatchUpdates completion handler, can that cause a retain cycle?

Say I have a UITableViewController subclass which has some function in it, eg: 说我有一个UITableViewController子类,它具有一些功能,例如:

class MyTableVC: UITableViewController {
    func doSomething() { ... }
}

and I add a function to it that calls performBatchUpdates with a completion handler which captures self: 然后向其中添加一个函数,该函数使用捕获自我的完成处理程序来调用performBatchUpdates

    func updateStuff() {
        tableView.performBatchUpdates(someUpdates, completion: { _ in 
            self.doSomething()
        }
    }

Is there a danger of creating a retain cycle? 是否存在创建保留周期的危险? If so, is the view controller guaranteed to be non-nil in the callback? 如果是这样,是否保证视图控制器在回调中不为null? ie If there's a possibility of a retain cycle, can I use [unowned self] or is it necessary to use [weak self] 例如,如果有保留周期的可能性,我可以使用[unowned self]还是有必要使用[weak self]

There is no major issue in your solution. 您的解决方案没有大问题。 self will only be retained until the completion of batch update which is fine. self只会保留到批量更新完成为止。 And I'd probably do the same not to complicate the code. 而且我可能会做同样的事情,以不使代码复杂化。

Regularly it is a bit better to still have weak or unowned just to maintain similar code style through your project. 通常,为了在您的项目中保持类似的代码风格而仍然拥有weakunowned为好。

If you decide to pick one of these, weak is the only safe option here. 如果您决定选择其中之一,则weak是此处唯一的安全选择。 For example, the view controller can be removed from the screen and deallocated while the table performs the update operation (the chance is really tiny but still exists) which will cause a crash in the result. 例如,可以在表执行更新操作时将视图控制器从屏幕上移开并重新分配(机会很小,但仍然存在),这将导致结果崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM