Usage Question concerning [weak self]


Rick Aurbach
 

I am doing some processing of network requests, and the response is processed in a background thread using a closure.

The closure executes some logic on the background thread and then (possibly) dispatched to the main thread. Something like
closure = { [weak self] (...) in
    if self?.foo {
        DispatchQueue.main.async { [weak self] in
            self?.xxx()
        }
    }
}

My question is do I actually need the second "[weak self]" reference? Or, having captured self, am I ok leaving it out?
My thought is that I need both because it is possible that by the time the main-thread code executes, the object referred to by "self" might have been deallocated. (Unlikely, but conceivable.)

Am I thinking about this correctly??

Thanks.


Ben Kennedy
 

On 23 Jun 2019, at 3:12 pm, Rick Aurbach via Groups.Io <rlaurb@...> wrote:

closure = { [weak self] (...) in
if self?.foo {
DispatchQueue.main.async { [weak self] in
self?.xxx()
}
}
}

My question is do I actually need the second "[weak self]" reference? Or, having captured self, am I ok leaving it out?
By my analysis the capture list in the DispatchQueue closure is unnecessary, because by that point `self` is already weak. You can prove this by adding a `weak var this = self` and change the `self`s to `this`es, then option-click on the inner `this` and see that it is indeed still weak.

b