Can this object be thrown away yet? Keeping track of how many places are still using an object is one way to answer this question.
The way it works is like this. When you first create an object it starts out with a reference count of zero. That just means that it’s not being used. You normally want to increase that reference count right away. Some libraries might even do this for you. The point is that if you intend to use and continue referring to some object instance, then you need to either increase the reference count or know for sure that it’s already been increased for you.
This shows that the object is being used in a single place in the code. You don’t have to go hunting through the code to find out where it’s being used. You can just ask the object itself what its reference count is. Now, whenever you’re done with the object, instead of deleting it, you instead release it. There’s usually a method on the object called release that you can call. This will cause the reference count to decrement by one. and if the count goes to zero, then the object can delete itself.
What happens when things go wrong? And how can things go wrong? What if two objects each refer to the other? In other words, each object has a reference counted data member of the other object and they’ve both added a reference to the other object to show that it’s in use.
This situation is called a cyclic dependency. It doesn’t have to be just two objects. Any cycle of at least two object can cause the problem. Maybe object A is holding a reference on object B which is then holding a reference on object C. You get a cyclic dependency if object C also has added a reference on object A. It forms a loop. None of the reference counts can go to zero and the objects are stuck.
Listen to the full episode to find out how to fix this problem.