1. Avoiding retain cycles caused by capturing ‘self’ in a closure in a class

Swift uses Automatic Reference Counting (ARC) to manage its memory allocation and deallocation. This means that Swift automatically allocates memory to objects and then frees up that memory when the object is no longer in use (this is done by tracking the number of references of each object, zero references lead to deallocation).

While ARC manages most of the memory management, a strong reference cycle can lead to memory leaks from your app.

A common use case for such kind of a retain cycle is when self is captured inside a closure in a class.

“A strong reference cycle can also occur if you assign a closure to a property of a class instance, and the body of that closure captures the instance.” — Swift.org

In the Mentorship iOS app, we had these retain cycles while making the network calls and assigning properties in the sink operator.

import Foundation
	import Combine

	class Members: ObservableObject {
	    @Published var membersResponseData = [MembersModel.MembersResponseData]()
	    private var cancellable: AnyCancellable?

	    func fetchMembers() {
	        cancellable = NetworkManager.callAPI(urlString: URLStringConstants.members)
	            .receive(on: RunLoop.main)
	            .catch { _ in Just(self.membersResponseData) }
	            .sink { members in
	                // RETAIN CYCLE : strong capturing of self in a closure in a class
	                self.membersResponseData = members
	        }
	    }
	}

A closure, like a class, is a reference type. Hence, by capturing self inside a closure in a class we make a retain cycle; since the closure is captured by the class and the class is captured by the closure. As a result, in the above code, the class Members will never be deinitialized (memory leak!).

Solution:

The strong reference cycle can be easily solved by capturing weak self in the closure.

.sink { [weak self] members in
    self?.membersResponseData = members
}

#swiftui #programming #ios #memory-leak #swift-programming

Two tips I got from Apple engineers to avoid Memory Leaks and increase efficiency
22.95 GEEK