[unowned self] not necessary

  @IBAction func addName(_ sender: UIBarButtonItem) {

    let alert = UIAlertController(title: "New Name",
                                  message: "Add a new name",
                                  preferredStyle: .alert)

    let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] action in

      guard let textField = alert.textFields?.first,
        let nameToSave = textField.text else {
          return
      }

      self.save(name: nameToSave)
      self.tableView.reloadData()
    }
   ...
  }

I think, using [unowned self] ( or [weak self] ) in this case don’t necessary, because alert object is just a variable in the function, not a property of class. Am I right ?

I think using “unowned” will sync up when objects are removed from memory. As per Apple’s documentation re: ARC, “use an unowned reference when the other instance has the same lifetime or a longer lifetime”.

You can read more in the section, Resolving Strong Reference Cycles Between Class Instances:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html

Also, in this case, unowned is referring to self, which is the class ViewController, not just a property or a method. In fact, if you tried to apply “unowned” to a property, you will get this error message:

“unowned” may only be applied to class and class-bound protocol types

1 Like

I agree with @tikhonov. My thinking is the closure capture list is not needed as this closure does not create a strong reference cycle between itself and the ViewController instance.

My observations:

  1. The closure is not assigned to an instance property of the ViewController instance (self).

  2. Even though the closure captures “self” (via instance method calls), the saveAction reference is locally scoped within the addName(_:slight_smile: function (it is not an instance property of the ViewController instance). Once the function finishes executing, the alert, saveAction and cancelAction references should be deallocated (including the closure).

  3. According to Apple’s documentation unowned and weak capture list’s should only be used if the closure is creating a strong reference cycle.

Perhaps I’m missing something else…

Any feedback or additional comments on this topic would be greatly appreciated. Thanks @tikhonov for raising this.

3 Likes

How to do the same in objective-c?