Skip to content

Instantly share code, notes, and snippets.

@aceontech
Created March 3, 2017 08:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aceontech/ec2484e506c222aaf7c1b788a07e7e0a to your computer and use it in GitHub Desktop.
Save aceontech/ec2484e506c222aaf7c1b788a07e7e0a to your computer and use it in GitHub Desktop.
Unit test for checking for retain cycles in Swift. Replace `CLASS_YOU_WANT_TO_TEST` with your class name.
func testCleanup() {
// Extend your class inline in order to add closure property `deinitCalled`,
// which indicates when/if your class's deinit() gets called
class ClassUnderTest: CLASS_YOU_WANT_TO_TEST {
var deinitCalled: (() -> Void)?
deinit { deinitCalled?() }
}
// Set up async expectation, which causes the test to wait for `deinitCalled`
// to be called
let exp = expectation(description: "exp")
// Initialize the class
var instance: ClassUnderTest? = ClassUnderTest()
// Set up up the `deinitCalled` closure, making the test succeed
instance?.deinitCalled = {
exp.fulfill()
}
// On a different queue, remove the instance from memory,
// which should call `deinit`, in order to clean up resources.
// If this doesn't cause `deinit` to be called, you probably have a
// retain cycle
DispatchQueue.global(qos: .background).async {
instance = nil
}
// Wait for max. five seconds for the test to succeed, if not,
// you may have a memory leak due to a retain cycle
waitForExpectations(timeout: 5)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment