Member-only story
Understanding Retain Cycles in Swift iOS
A Guide to Understanding and Preventing Memory Leaks in Your iOS Apps
A retain cycle occurs when two (or more) objects hold strong references to each other, preventing ARC (Automatic Reference Counting) from deallocating them even when they should no longer exist. This results in a memory leak because the reference count for each object never reaches zero.
How a Retain Cycle Happens
Consider two classes, Person
and Apartment
, where a Person
has an apartment
property and an Apartment
has a tenant
property. If both properties are strong references (the default in Swift), they hold on to each other, creating a cycle.
Example Code
class Person {
let name: String
var apartment: Apartment? // Strong reference to Apartment
init(name: String) {
self.name = name
}
deinit {
print("\(name) is being deinitialized")
}
}
class Apartment {
let unit: String
var tenant: Person? // Strong reference to Person
init(unit: String) {
self.unit = unit
}
deinit {
print("Apartment \(unit) is being deinitialized")
}
}
// Creating instances
var john: Person? = Person(name: "John")
var unit4A: Apartment? = Apartment(unit: "4A")
// Setting up the mutual references (retain cycle!)…