I have created a UIAlertController and added a text field into it. The problem is that the after I dismiss the alertcontroller, it is not deallocating and shows in the memory graph.
let alertController = UIAlertController(title: "Enter link", message: nil, preferredStyle: .alert)
alertController.addTextField { (textField) in
textField.placeholder = "www.xxx.com"
}
let cancel = UIAlertAction(title: "CANCEL", style: .cancel, handler: nil)
let ok = UIAlertAction(title: "SUBMIT", style: .default) { [weak self] (_) in
guard let self = self else { return }
guard let textFields = alertController.textFields, let textField = textFields.first else { return }
if let text = textField.text {
}
}
alertController.addAction(cancel)
alertController.addAction(ok)
present(alertController, animated: true, completion: nil)
However, if I remove the alertController.addTextField
then it gets deallocated and it does not exist in the memory graph.
I tried checking if there are any memory leaks introduced due to my code but found none.
You're retaining the alertController
inside of "ok" alert action, which is in turn retained by UIAlertController
.
That's a retain cycle, neither of objects will be able to release each other.
You should avoid that, perhaps by using a weak reference, i.e:
let ok = UIAlertAction(title: "SUBMIT", style: .default) { [weak alertController] (_) in
// Upgrade weak to strong reference
guard let alertController = alertController else { return }
// Do your thing
}