- Object–Oriented Programming with Swift 2
- Gastón C. Hillar
- 397字
- 2021-07-23 14:29:41
Understanding automatic reference counting
Automatic reference counting is very easy to understand. Imagine that we have to distribute the items that we store in a box. After we distribute all the items, we must throw the box in a recycle bin. We cannot throw the box to the recycle bin when we still have one or more items in it. Seriously, we don't want to lose the items we have to distribute because they are very expensive.
The problem has a very easy solution; we just need to count the number of items that remain in the box. When the number of items in the box reaches zero, we can get rid of the box.
Tip
One or more variables can hold a reference to a single instance of a class. Thus, it is necessary to count the number of references to an instance before Swift can get rid of an instance. When the number of references to a specific instance reaches zero, Swift can automatically and safely remove the instance from memory because nobody needs this specific instance anymore.
For example, you can create an instance of a class and assign it to a variable. The automatic reference counting mechanism registers the reference and knows that there is one reference to this instance. Then, you can assign the same instance to another variable, and therefore, the automatic reference counting mechanism will increase the reference count for the single instance to two.
After the first variable runs out of scope, the second variable that holds a reference to the instance will still be accessible. The automatic reference counting mechanism will decrease the reference count for the single instance to one as a result of the first variable running out of scope. At this point, the reference count for the single instance is equal to one, and therefore, the instance must still be available—that is, we need it alive.
After the second variable runs out of scope, there are no more variables that hold a reference to the instance; therefore, the automatic reference counting mechanism will decrease the reference count for the single instance to zero and mark it as disposable. At this point, the instance can be safely removed from memory.
Tip
The automatic reference counting mechanism can remove the instance from memory at any time after the reference count for the instance reaches zero.
- Spring 5.0 Microservices(Second Edition)
- 數(shù)據(jù)庫系統(tǒng)教程(第2版)
- Effective C#:改善C#代碼的50個有效方法(原書第3版)
- 簡單高效LATEX
- Access 2010數(shù)據(jù)庫基礎(chǔ)與應(yīng)用項目式教程(第3版)
- Mastering LibGDX Game Development
- Hands-On Swift 5 Microservices Development
- 零基礎(chǔ)輕松學(xué)SQL Server 2016
- Corona SDK Mobile Game Development:Beginner's Guide(Second Edition)
- Learning Concurrent Programming in Scala
- OpenCV with Python By Example
- Android應(yīng)用開發(fā)實戰(zhàn)
- 創(chuàng)意UI Photoshop玩轉(zhuǎn)移動UI設(shè)計
- Learning Android Application Testing
- 大數(shù)據(jù)時代的企業(yè)升級之道(全3冊)