- Object–Oriented Programming with Swift 2
- Gastón C. Hillar
- 263字
- 2021-07-23 14:29:40
Understanding deinitialization and its customization
At some specific times, our app won't require to work with an instance anymore. For example, once you calculate the perimeter of a regular hexagon and display the results to the user, you don't need the specific RegularHexagon
instance anymore. Some programming languages require you to be careful about leaving live instances alive, and you have to explicitly destroy them and deallocate the memory that it consumed.
Swift uses an automatic reference counting, also known as ARC, to automatically deallocate the memory used by instances that aren't referenced anymore. When Swift detects that you aren't referencing an instance anymore, Swift executes the code specified within the instance's deinitializer before the instance is deallocated from memory. Thus, the deinitializer can still access all of the instance's resources.
Tip
You can think of deinitializers as equivalents of destructors in other programming languages such as C# and Java. You can use deinitializers to perform any necessary cleanup before the objects are deallocated and removed from memory.
For example, think about the following situation: you need to count the number of instances of a specific class that are being kept alive. You can have a variable shared by all the classes. Then, customize the class initializer to atomically increase the value for the counter—that is, increase the value of the variable shared by all the classes. Finally, customize the class deinitializer to atomically decrease the value for the counter. This way, you can check the value of this variable to know the objects that are being referenced in your application.
- Web前端開發(fā)技術(shù):HTML、CSS、JavaScript(第3版)
- HTML5移動Web開發(fā)技術(shù)
- Visual Basic 6.0程序設(shè)計(jì)計(jì)算機(jī)組裝與維修
- Instant Apache Stanbol
- Mastering QGIS
- Python高級編程
- Python 3網(wǎng)絡(luò)爬蟲實(shí)戰(zhàn)
- Python數(shù)據(jù)可視化之Matplotlib與Pyecharts實(shí)戰(zhàn)
- Learning FuelPHP for Effective PHP Development
- 組態(tài)軟件技術(shù)與應(yīng)用
- Android系統(tǒng)級深入開發(fā)
- Python之光:Python編程入門與實(shí)戰(zhàn)
- 細(xì)說Python編程:從入門到科學(xué)計(jì)算
- Struts 2.x權(quán)威指南
- 寫給大家看的Midjourney設(shè)計(jì)書