As you know in Objective-C every object has a reference counter which hold the number of strong references to an object.
When an object has not strong references the counter is 0 and the object itself is free to be deallocated.

You can have two different types of references: strong and weak.
Anytime a pointer variable stores the address of an object, that object has an owner and will stay alive; this is the default behavior: strong.
However, optionally, you can decided to not take ownership of an object it points to; this kind of variable has a weak references to the object.

A weak reference is quite useful in order to avoid the “retain cycle” (we have already discussed this in a previous post. another great post here by CocoaWithLove): basically, a retain cycle occurs when two – or more than two – objects have strong references between each other. When this happens, ARC cannot handle memory in the correct way and none of your variables can be released, even if they are not being used by the code: they mantain each other alive.

Our problem

Sometimes you might need to store one or more objects into a collection (NSMutableArray/Set/Dictionary) using a weak reference. This is a problem because the default behavior of these collections classes is to retain taken objects.

This is a small trip around the many possible ways to solve this problem.

Continue reading…