官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 天镇县| 镇雄县| 宁乡县| 乌兰浩特市| 依安县| 新巴尔虎左旗| 邳州市| 合肥市| 平陆县| 佳木斯市| 车致| 子洲县| 理塘县| 广饶县| 印江| 宣汉县| 桐庐县| 蓝田县| 冷水江市| 景洪市| 荥阳市| 扎鲁特旗| 中牟县| 宣恩县| 漾濞| 通辽市| 隆安县| 锡林郭勒盟| 乐陵市| 张家川| 曲沃县| 仙游县| 洛阳市| 寿宁县| 聂拉木县| 象山县| 新巴尔虎右旗| 兴业县| 深圳市| 集贤县| 白沙|