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?
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With