Junior — Middle
When does resource release and destructor call occur for an object in a program?
sobes.tech AI
Answer from AI
In iOS (and generally in object-oriented programming with Swift or Objective-C), the destructor (deinit in Swift) is called automatically when the object is no longer accessible, that is, when the reference count to the object reaches zero. This happens when all strong references to the object are released, after which the system calls the destructor to free resources associated with the object (for example, closing files, freeing memory, stopping timers, etc.).
Example in Swift:
class MyClass {
deinit {
print("Object is being destroyed, releasing resources")
}
}
var obj: MyClass? = MyClass()
obj = nil // deinit will be called here
Thus, resource release and destructor invocation occur when the last strong reference to the object is removed.