- 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.
- Learning Scala Programming
- 從零構建知識圖譜:技術、方法與案例
- 國際大學生程序設計競賽中山大學內部選拔真題解(二)
- 深入淺出WPF
- Oracle 12c中文版數據庫管理、應用與開發實踐教程 (清華電腦學堂)
- Haskell Data Analysis Cookbook
- Oracle GoldenGate 12c Implementer's Guide
- Spring MVC+MyBatis開發從入門到項目實踐(超值版)
- 寫給程序員的Python教程
- Python趣味編程與精彩實例
- R語言數據挖掘:實用項目解析
- 視窗軟件設計和開發自動化:可視化D++語言
- Learning C++ by Creating Games with UE4
- INSTANT Lift Web Applications How-to
- 鋁合金陽極氧化與表面處理技術(第三版)