alexisSchreier
alexisSchreier

Reputation: 677

Do I need to capture self weakly inside a UIAlertController's action completion handler

I've read that self doesn't need to be captured weakly in a UIAlertController action completion handler if the UIAlertController reference is weak. The reason being that UIAlertController is designed to release everything once it's done executing, provided that you hold a weak reference to it.

Source here.

Here is a hypothetical example:

let alert = UIAlertController(title: "title", message: "message", preferredStyle: .alert)

// The action's completion handler captures the alert controller weakly, but self is not captured weakly
let action = UIAlertAction(title: "action title", style: .default, handler: { [weak alert] _ in
    guard let alertController = alert else {
        return
    }
    // The alert controller's action triggers a server call method owned by self
    self.serverCall { result in

            // We use the alertController inside the closure
            print(alertController.actions)

            DispatchQueue.main.async {
                // Do stuff on the main thread with the result
            }
    }
})

alert.addAction(action)

Is this a valid way to keep a weak reference to the UIAlertController?

Will keeping a strong reference to self, in this case, cause a retain cycle or not?

Upvotes: 0

Views: 1390

Answers (2)

scorpiozj
scorpiozj

Reputation: 2687

In the example code, UIAlertController is not a var of the view controller. In this case, you don't need weakify the self in the action's handler (btw, the parameter of the handler should be UIAlertAction -> Void).

When the view controller which calls present retains the UIAlertController, it needs [weak self] in the handler. In other cases it doesn't need weak.

Besides, the link you provides clarifies it.

Upvotes: 1

quynhbkhn
quynhbkhn

Reputation: 732

Is this a valid way to keep a weak reference to the UIAlertController?:

Yes, it's true

Will keeping a strong reference to self, in this case, cause a retain cycle or not? weak self will reference with value, when base class is destroy, it realy free memory. So it not retain cycle.

Upvotes: 1

Related Questions