Retain cycle with DisptachQueue

Could this become a retain cycle?

class ViewController: UIViewController {
    
    let queue = DispatchQueue(label: "some queue")
    
    init() {
        super.init(nibName: nil, bundle: nil)
        queue.async {
            self.fetchData()
        }
    }
    ...
}
1 Like

I think no. self is only retained as long as the dispatched block executes but no longer than that.

1 Like

You are right that it is a retain cycle, but it's a temporary and harmless one because it'll disappear as soon as the enqueued task is finished.

You still could make self weak in the closure to allow the view controller to disappear before the async task runs, which in turns would allow the task to abort early when if the view controller disappeared.

4 Likes

From what I tested it with the memory graph, it does not, but I’m not quite sure why.

As mentioned this cycle is temporary. If you change async to asyncAfter(.now() + 10) the cycle will exist for 10 seconds, then break, and with async it breaks much sooner.

3 Likes