6.8 Instance reference feature and Swift's memory management [Swift original tutorial]

Original: http://coolketang.com/staticCoding/5a99261fd50eee2ea3037740.html

1. The development language uses automatic reference counting to track and manage the memory allocated by the application. The memory occupied by instances of these classes is automatically released when the instances are no longer in use. 



2. This lesson will demonstrate the management of instance references by automatic reference counting. First, define a class for creating instances. 


3. Add a property to the class. 


4. Add an initialization method to set the value of the property. 


5. Then add a destructor method that will be called when the reference count of the instance of the class reaches 0 (maybe not immediately). 


6. Then initialize an instance object of the class, and initialize the value of the object's properties. 


7. Assign the object to two other variables so that the object's reference count is 3. 


8. As you can see from the result on the right, all three variables are references to the same instance of the class. 


9. Then set the first reference of the instance to null, the result on the right shows that the reference is already null, and the reference count of the instance object becomes 2. 


10. It can be seen from the opened console that the destructor method has not been called, otherwise the corresponding log will be output. 


11. Continue to set the second reference of the instance to null, and the reference count is reduced to 1. Since the instance is still referenced, no destructor log is output. 


12. The third reference of the instance is also set to null, and the reference count is reduced to 0. Since the instance is no longer referenced, the destructor log is output to the console. 


This article is organized from: "Swift4 Interactive Tutorial", the real [Hands-on] teaching mode, get started with iOS development and Swift language at the fastest speed, free download from Apple Store App Store: https://itunes.apple.com/cn/app/id1320746678 , or scan the QR code at the bottom of this page . Course supporting material download address: data download


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325775928&siteId=291194637