Junior — Middle
What reasons make using Unowned less preferable in certain situations?
sobes.tech AI
Answer from AI
Using unowned in iOS (Swift) is less preferred in situations where there is a risk that the object referenced by unowned may be deallocated before the reference is used. Unlike weak, unowned is not optional and does not become nil upon deallocation, so accessing such a reference after deallocation will cause a runtime crash.
Reasons to avoid unowned:
- If the object's lifecycle does not guarantee that the reference will always be valid.
- In complex mutual references where the order of object deallocation is unclear.
In such cases, it is better to use weak, which automatically becomes nil, preventing a crash.
Example:
class A {
unowned var b: B
init(b: B) { self.b = b }
}
class B {
var a: A?
}
If object B is deallocated before A, accessing b in A will cause an error.