iOS memory leaks check list

Panagiotis Kompotis
2 min readMar 29, 2020

At first we don’t know what a memory leak is. However sooner or later, every iOS developer will need to deal with them. We will see common cases when they occur, and what we can do to resolve them.

Memory leaks occur in iOS when strong reference cycles take place. iOS deallocates an object when the count to it’s references becomes zero. Thus when two strong references exist between two objects since they are pointing to each other, the reference count cannot be zero. As a result the os cannot reclaim the memory.

Strong reference cycle

Checklist

  1. Delegates. Deleageate objects need to be declared as weak optional variables, so that the os can reclaim the memory. In case that is not done, a strong reference cycle is created, as the delegate object and the class conforming to the protocolstrongly reference each other.

2. Closures.On Classes where closures are implemented (and self is used inside the closure), classes hold strong references to the closures. Thus we have a cycle. The class references the closure and closure reference the class. Consequently the class instance can not be removed from memory.
In order to break the cycle the self instance should be declared as weak or unowned inside the closure.

3. Strong reference cycles. Theses occur when two object reference each other strongly (by default each reference is a strong reference in Swift). Therefore no object can be deallocated, because the reference count is not zero. Since the os reclaims object’s allocated memory when the count of all references to that object is zero, it cant be deallocated.
Lets say for instance that something like this occurs:

In that case a leak takes place, because ClassA holds a reference to ClassB and vice versa. To break the memmory leak one reference needs to be declared as weak.

Hope you enjoyed this article, and gained an understanding on common places to look for leaks in your project. If you have any question or you want to leave feedback, feel free to comment.

--

--