Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test for dealloc with ARC in iOS

I'd like to write an iOS unit test for a dealloc method that (basically) removes the object as the delegate of another object.

- (void) dealloc {
    someObject.delegate = nil;
}

However I can't call dealloc directly when using ARC. What would be the best way to write this unit test?

like image 259
hpique Avatar asked Dec 03 '11 18:12

hpique


Video Answer


2 Answers

Assign an instance to a weak variable:

MyType* __weak zzz = [[MyType alloc] init];

The instance will be dealloced right away.

Alternatively, you can disable ARC on your unit test file and call dealloc.

like image 171
Sergey Kalinichenko Avatar answered Sep 29 '22 12:09

Sergey Kalinichenko


A better solution is simply

- (void)testDealloc
{
    __weak CLASS *weakReference;
    @autoreleasepool {
        CLASS *reference = [[CLASS alloc] init]; // or similar instance creator.
        weakReference = reference;

        // Test your magic here.
        [...]
    }
    // At this point the everything is working fine, the weak reference must be nil.
    XCTAssertNil(weakReference);
}

This works creating an instance to the class we want to deallocate inside @autorealase, that will be released (if we are not leaking) as soon as we exit the block. weakReference will hold the reference to the instance without retaining it, that will be set to nil.

like image 33
7ynk3r Avatar answered Sep 29 '22 10:09

7ynk3r