I know that we can use strong self in DispatchQueues when we call it directly in the code, for example:
func foo() {
DispatchQueue.global().async {
print(self.someProperty)
}
}
But what about my custom queue, if I keep it in the class? Should I use weak self
or it works the same and there is no need to worry about leaks?
class MyClass {
let queue = DispatchQueue(
label: "MyQueue",
qos: .userInitiated
)
func foo() {
queue.async { [weak self] in
guard let self else { return }
print(self.someProperty)
}
}
}
In this case my custom queue is stored in a class variable and probably I should use weak self
. Or not?
queue.async
closure does retain self
without [weak self]
. However, it's temporary, it will disappear immediately when dequeued. So there is no retain cycle here.
AFAIK, it's more like data flow than a retain cycle.
[weak self]
: you might want to exit the scope early.[weak self]
: you want to retain the object until the block is executed.