Is weak self needed for table view cell button closure

后端 未结 3 986
忘掉有多难
忘掉有多难 2021-01-27 04:17

In trying to avoid retain cycles, would using [weak self] in in a UITableViewCell button action be necessary? Example:

in ViewController\'s cellForRow<

3条回答
  •  有刺的猬
    2021-01-27 04:54

    The key line to think about is:

    var buttonAction: ((UITableViewCell) -> Void)?
    

    You are offering to store a function long-term in an instance property.

    Now think about who refers to / owns whom. The view controller owns its view which is-or-owns the table view which owns the cell. Meanwhile the cell owns the function. If the function refers strongly to any of the objects I just mentioned, that is a retain cycle. It is a classic retain cycle, the absolute model of how retain cycles get made.


    [I would like to add a word about how I test for these things. There's a really cheap and easy way: wrap your view controller up in a navigation controller plus a blank root view controller, so that you can push your view controller onto it. Implement deinit in your view controller. Now run the app, push your view controller, play with it for a bit, and pop it with the Back button. If deinit isn't called, you've got a retain cycle.]

提交回复
热议问题