What is the primary issue with the following Swift code snippet concerning Automatic Reference Counting (ARC) and Grand Central Dispatch (GCD)?

iOS interview question for Intermediate practice.

Answer

A retain cycle occurs because the closure strongly captures self, and self implicitly owns the dispatched work.

Explanation

The code creates a strong reference cycle. The self instance within the DispatchQueue.main.async closure strongly captures self to call self.updateName(). Because the MyClass instance holds a reference to this operation (by having initiated it), a circular dependency is formed. This can prevent the deallocation of the MyClass instance if it's supposed to be released while the async operation is still pending. The solution is to use a [weak self] capture.

Related Questions