I use [weak self]
when I have a completion block that refers to properties of my class object. However, sometimes I have a completion block that doesn't refer to any properties, but the class object could disappear and deinit. Should I be using [weak self]
or not? It usually gives a warning Variable 'self' was written to, but never read
when I do...
doSomeFunction() { [weak self] in
// No references to self here
}
“Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialisation.” Save this answer.
because block are mean to be executed at a later time, so it need to keep strong reference to all the object it access. Block can be executed MANY TIMES, so IT WON'T RELEASE self AFTER this ran. When you nil out the block, it will be dealloc, hence it will decrease the reference count to all the objects it access.
In Swift, [weak self] prevents closures from causing memory leaks in your application. This is because when you use [weak self], you tell the compiler to create a weak reference to self. In other words, the ARC can release self from memory when necessary.
Difference between weak reference and unowned referenceThe weak reference is an optional type, which means weak reference will set to nil once the instance it refers to frees from memory. On the other hand, unowned reference is a non-optional type, it never will be set to nil and always have some value.
Capturing the variables, happens only when you use it internally, a closure will NEVER capture the variables by default (not like Java inner class which ALWAYS captures this
), so, it you use a variable (including self
) inside the closure, it is captured.
Also you can manually capture the variables using the [weak self]
, [weak your_variable_here]
, [unowned self]
, [unowned your_variable_here]
, [self]
or [your_variable_here]
If the compiler tells you variable "self" is written to but never read from
, it means that you didn't use self
inside, so it is completely safe not to use [weak self]
, because self
will NOT be captured, because it is not used.
weak self
or unowned self
is needed only when your closure captures self
, and escapes the function it is passed to, especially if it is saved in a variable.
Refer to Closures in Apple's Official Swift Documentation
No you don't need to. Swift won't do anything with the reference that isn't used so NOT using it does the same as using it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With