Created
March 3, 2017 08:14
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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