Middle
How do retain counts work with strong references in iOS?
sobes.tech AI
Answer from AI
When an object is assigned to a variable with a strong reference, the reference count of the object increases by 1. When the strong reference is set to nil or goes out of scope, the reference count decreases by 1. The object is deallocated when its reference count reaches zero and it no longer has strong references.
Example:
class MyObject {
deinit {
// Called when the object is deallocated
print("MyObject deallocated.")
}
}
var object1: MyObject? = MyObject() // object1 - strong reference, MyObject reference count == 1
var object2 = object1 // object2 - strong reference, MyObject reference count == 2
object1 = nil // Strong reference object1 is set to nil, MyObject reference count == 1
object2 = nil // Strong reference object2 is set to nil, MyObject reference count == 0
// MyObject is deallocated