Reputation: 1251
When I started developing Swift code I wasn't that experienced handling memory leaks, so it take some time to me to figure out that what is a retain cycle, what is ARC, and why I should use weak
or unowned
inside my closures that was creating those retain cycles.
By default I always add this piece of code in closures that is referencing self:
class MyController: UIViewController {
var myClosure: (Data?, Error?)?
override viewDidLoad() {
self.myClosure = { [weak self] (data, err) in
guard let self = self else { return }
self.present(someVC, animated: true)
}
}
}
That code is something very common and using this weak
modifier and also unwrapping self
is something that is almost a default code.
That makes me question. If I have to always add a weak self
in code that is referencing self
and not allowing the class to be deinit WHY Apple don't make it a default behaviour on the language so we don't need to have this code repeating everywhere on our code base?
Upvotes: 0
Views: 45
Reputation: 11
You don't have to always use weak self
when referencing self
in a closure.
But in this particular case you do have to and it was explained here
Upvotes: 0