Robert
Robert

Reputation: 38213

How to test for UIViewController retain cycles in a Unit test?

I want to unit test for retain cycles in in a custom view controller subclass unit test, but hit an issue.

Triggering the view property seems to mean dealloc is never called. Any ideas how to fix this?

- (void)testViewControllerHasNoRetainCycles
{
    UIViewController *viewController = [[UIViewController alloc] init];

    // Trigger `veiwDidLoad`
    // commenting out this line passes the test
    [viewController view];

    // Make a weak ref and set the original ref to nil
    // This should mean the weak ref also becomes nil
    // since there is nothing left retaining it
    // (unless there is a retain cycle)
    __weak UIViewController * weakViewController = viewController;
    viewController = nil;

    // This fails
    XCTAssertNil(weakViewController);
}

Upvotes: 1

Views: 237

Answers (1)

Binary Pulsar
Binary Pulsar

Reputation: 1209

Wrapping the above in an autorelease pool worked for me:

__weak UIViewController * weakViewController;
@autoreleasepool {
    UIViewController *viewController = [[UIViewController alloc] init];
    [viewController view];
    weakViewController = viewController;
    viewController = nil;
}
XCTAssertNil(weakViewController);

Upvotes: 1

Related Questions