AdvancedLesson 13 of 16
ARC, weak & Retain Cycles – Swift
How Swift manages memory and how you avoid memory leaks.
Swift uses ARC (Automatic Reference Counting): every class object counts how many strong references point to it. When the counter drops to 0, the object is freed immediately (deinit runs). Value types (structs, enums) need no ARC; they live within their scope.
class Person {
let name: String
init(name: String) { self.name = name; print("\(name) created") }
deinit { print("\(name) released") }
}
var p: Person? = Person(name: "Ada") // count = 1
var q = p // count = 2
p = nil // count = 1
print("p is nil")
q = nil // count = 0 -> deinit
// Ada created / p is nil / Ada releasedIf two objects point to each other strongly, a retain cycle arises: both keep each other alive, and neither is ever freed (memory leak). The solution: one side holds only weakly (weak, automatically becomes nil, must be an optional var) or unowned (never nil, crash on error).
class Besitzer {
let name: String
var haustier: Haustier?
init(name: String) { self.name = name }
deinit { print("Owner \(name) released") }
}
class Haustier {
let name: String
weak var besitzer: Besitzer? // weak breaks the cycle
init(name: String) { self.name = name }
deinit { print("Pet \(name) released") }
}
var ada: Besitzer? = Besitzer(name: "Ada")
ada?.haustier = Haustier(name: "Rex")
ada?.haustier?.besitzer = ada
ada = nil
// Owner Ada released
// Pet Rex releasedClosures can also create cycles if they capture self and are themselves held by self. A capture list solves this:
class Sensor {
var wert = 21
var handler: (() -> Void)?
func konfiguriere() {
handler = { [weak self] in
guard let self else { return }
print("Value:", self.wert)
}
}
deinit { print("Sensor released") }
}
var s: Sensor? = Sensor()
s?.konfiguriere()
s?.handler?() // Value: 21
s = nil // Sensor released (no cycle)TipValue types are usually the simplest solution to memory problems: structs have no cycles. With
isKnownUniquelyReferenced(&objekt) you check uniqueness (the basis for copy-on-write in your own types). The Debug Memory Graph tool in Xcode shows leaks graphically.Warning
unowned is only safe if the object is guaranteed to live at least as long as the reference. When in doubt, use weak: better a nil check than a crash.