Thursday, August 17, 2023

How to Automate Memory Leak Detection With XCTest

Dan Torres:

Inside the addTearDownBlock, we can assert if sut and spy are deallocated by asserting if they’re nil. We hold sut and spy 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 XCTestExpectations 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.


Comments RSS · Twitter · Mastodon

Leave a Comment