Prevent memory leaks with autoreleasepool in unit tests

Tram Ho

Memory leaks often occur without any notice. Although using a weak reference for self in closures helps a lot, but that is not enough. We can use memory graph debugging or Xcode Instruments to find and resolve memory errors. But it is quite complicated and time consuming.

Thankfully we have a simpler way, by using unit tests. This method does not prevent all leaks, but it is still very effective.

Prevent memory leak with unit tests

Writing a unit test by combining a weak reference with an autoreleasepool will help determine the release (dealloc) easier. It can check to see if the deinit of a class has been called and the memory has been freed.

In the example below, we will check to see if a view controller has been released. By creating an extension method in XCTestCase , we can easily add it to any view controller unit test. Besides, it is a good way to check if the view controller has been released properly.

This extension creates a weak reference of the view controller created in the closure. Then, we present and dismiss that controller to check that the weak reference has become nil .

If the view controller is held down, the logic is in trouble and the test fails.

To confirm whether the weak reference is nil or not, we use another extension method in XCTestCase very handy when testing a certain condition.

XCTest API provides a nice API for generating expectation for notifications, predicates or KVO, but cannot use it to confirm whether a weak reference is really nil or not. The new extension method will do that. It will check in a period of time to see if the given condition is satisfied or not.

The use of an autoreleasepool

Without autoreleasepool, one cannot check if a weak reference has actually been released. All references in the autoreleasepool closure will be released when they drain, if no strong reference exists.

Share the news now

Source : Viblo