How to Automate Memory Leak Detection With XCTest
Inside the
addTearDownBlock
, we can assert ifsut
andspy
are deallocated by asserting if they’renil
. We holdsut
andspy
with weak references so that they won’t be strongly retained when executing the block.[…]
But adding this block to all your tests may reduce readability. So we can add an extension to
XCTestCase
, which will allow us to use it in any test. We would also add the file and line so the failure message can be at the exact line and file where the test failed.
I’ve found this sort of thing very helpful. I don’t recall why I didn’t use weak closure captures. Instead, I’ve been using associated objects that fulfill XCTestExpectation
s when they’re deallocated. Sometimes it takes a run loop cycle before objects are deallocated.
In order for this to work, you have to be careful of when you and Cocoa autorelease objects. For example, creating an NSWindow
or setting its title will end up extending the life of its view controller. So does changing the selected tab view item or some other tab view properties. You may think you’re avoiding leaks by using NSHashTable
to store weak references, but adding or reading the objects causes them to be retained and then autoreleased.
See also: Bruno Rocha, Paul Samuels, John Sundell.
Previously:
- Avoiding Implicit Retain Cycles When Using Swift Function References
- Dealing With Weak in Closure-based Delegation
- Automatic Memory Leak Detection on iOS