Swift Deinitialization
A deinitializer is called immediately before an instance of a class is released. Use the keyworddeinitto indicate the deinitializer, similar to how the initializer usesinitto indicate it. Deinitializers apply only to class types.
Deinitialization Principles
Swift automatically releases instances that are no longer needed to free up resources.
Swift handles memory management of instances through Automatic Reference Counting (ARC).
Generally, you do not need to manually clean up when your instance is released. However, when you are using your own resources, you may need to perform some additional cleanup.
For example, if you create a custom class to open a file and write some data, you may need to close the file before the class instance is released.
Syntax
In the class definition, each class can have at most one deinitializer. The deinitializer takes no parameters and is written without parentheses:
deinit {
// 执行析构过程
}
Example
var counter = 0; // 引用计数器
class BaseClass {
init() {
counter += 1;
}
deinit {
counter -= 1;
}
}
var show: BaseClass? = BaseClass()
print(counter)
show = nil
print(counter)
The output of the above program execution is:
1 0
After the show = nil statement is executed, the counter decreases by 1, and the memory occupied by show is released.
var counter = 0; // 引用计数器
class BaseClass {
init() {
counter += 1;
}
deinit {
counter -= 1;
}
}
var show: BaseClass? = BaseClass()
print(counter)
print(counter)
The output of the above program execution is:
1 1Other Extensions