Chapter 1: HitList Page 26

In the code sample section, for the saveAction, there is a closure clause has been used for the textfield.
I don’t understand why [unowned self] action as the closure parameter declared there, because we never use it in the closure. What if I change [unowned self] action to _, is that make more sense since we will never use the parameter in this closure?
Thanks in advance!

@mobetta The closure declares a capture list and captures self as an unowned reference in order to avoid ownership cycles.

You can read more about how memory management works in Swift in our Swift Apprentice book:

https://store.raywenderlich.com/products/swift-apprentice

I hope this helps. Please let me know if you have any other questions or issues regarding the whole thing. Thank you! :]

Can you explain where a strong reference cycle is hiding in that closure? As far as I can tell:

  1. The saveAction specifies a closure which captures self, i.e. the ViewController. Therefore, if at some point the ViewController needed to be destroyed, the destruction couldn’t happen because the closure still has a reference to the ViewController.

  2. The save action is added to the alert controller, and iOS tucks the alert controller away somewhere. If at some point the alert controller needed to be destroyed, the destruction couldn’t happen because the ViewController has a reference to the alert controller ?? Does the alert controller somehow get saved as a property of the ViewController?

Or, is there some three way, circular strong reference cycle that involves another object?

Or, is it appropriate to use unowned/weak for half a strong reference cycle? For instance, in this example is it appropriate to declare that the ViewController should be destroyed if the only reference to the ViewController is inside an alert controller–even if the ViewController does not have a reference back to the alert controller?

This topic was automatically closed after 166 days. New replies are no longer allowed.