简体   繁体   中英

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:

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

and I add a function to it that calls performBatchUpdates with a completion handler which captures self:

    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? ie If there's a possibility of a retain cycle, can I use [unowned self] or is it necessary to use [weak self]

There is no major issue in your solution. self will only be retained until the completion of batch update which is fine. 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.

If you decide to pick one of these, weak is the only safe option here. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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