original articles, welcome reprint. Reprint Please specify: Dongsheng's blog
In contrast to the construction process, when the instance is finally released, some resources need to be cleared, which is the process of destruction. A special method is also called during the destruction process.Deinit, called Destructors. DestructorsDeinitThere are no return values, no parameters, and no parentheses for the arguments, so you cannot overload them.
Here's a look at the sample code:
class Rectangle {
var width: Double
var height: Double
init (width: Double, height: Double) {
self.width = width
self.height = height
}
init (W width: Double, H height: Double) {
self.width = width
self.height = height
}
deinit {// Destructor is defined
print ("Call the destructor ...")
self.width = 0.0
self.height = 0.0
}
}
var rectc1: Rectangle? = Rectangle (width: 320, height: 480) // instance rectc1
print ("Rectangle: \ (rectc1! .width) x \ (rectc1! .height)")
rectc1 = nil // conditions that trigger the destructor call
var rectc2: Rectangle? = Rectangle (W: 320, H: 480) // instance rectc2
print ("Rectangle: \ (rectc2! .width) x \ (rectc2! .height)")
rectc2 = nil // conditions that trigger the destructor call
A destructor is called when the instance is assigned a value of Nil , which means that the instance needs to free up memory, call the destructor before releasing it, and then release it.
The results of the operation are as follows:
Rectangular : 320.0 x 480.0
call destructor ...
Rectangular : 320.0 x 480.0
call destructor ...
destructors apply only to classes and cannot be applied to enumerations and struct bodies. A similar approach toC + +is also called a destructor, the difference is thatC + +is often used to release memory resources that are no longer needed. And inSwift, memory management uses an automatic reference count (ARC), you do not need to dispose of unnecessary instance memory resources in the destructor, but there are still some cleanup tasks that need to be done here, such as closing files and so on.
Welcome to follow Dongsheng Sina Weibo@tony_Dongsheng.
Learn about the latest technical articles, books, tutorials and information on the public platform of the smart Jie classroom
?
More ProductsIOS,Cocos, mobile Design course please pay attention to the official website of Chi Jie Classroom:http://www.zhijieketang.com
Smart-Jie Classroom Forum Website:http://51work6.com/forum.php
Swift 2.0 Study Notes (day 40)-destructors