I'm new to Automatic reference counting and memory leaks and have (maybe) simple questions about them.
Now I get the general idea of what ARC thinks and how to avoid memory leaks, and my question is if a function has closure and requires to use self in that block, do I always need to write [weak self]
to avoid the memory leaks?
For example...
I just made a class called ViewControllerA, and it has a function, showDeleteAlert, which delete item by the target index and target id. (sorry it's just a random class and function). In the showDeleteAlert function's delete action, there is a closure to access dataSource class's delete function. I thought I need to use [weak self]
in the closure, since the ViewControllerA has a strong reference to showDeleteAlert function and showDeleteAlert function use self in the closure, which I think it has a strong connection to the ViewControllerA. Therefore, I put the [weak self]
to avoid memory leaks. In that case, do I need a weak self in the closure? (if not, could you explain why I don't need a weak self please?)
class ViewControllerA: UIViewController {
private var dataSource = MyDataSource()
private var targetIndex = Int()
private var targetId = String()
func showDeleteAlert() {
let deleteAction = UIAlertAction(title: "DELETE", style: .destructive) { [weak self] _ in
guard let strongSelf = self else {
return
}
strongSelf.dataSource.delete(by: strongSelf.targetId, at: strongSelf.targetIndex, completion: strongSelf.reloadVC)
}
let cancelAction = UIAlertAction(title: Alert.ButtonTitle.cancel, style: .cancel)
self.showAlert(title: alertTitle, message: nil, actions: [deleteAction, cancelAction], style: .actionSheet, completion: nil)
}
func reloadVC() {
// do something for reload VCA
}
}