在iOS中使用ARC进行dealloc的单元测试

hpi*_*que 6 unit-testing objective-c ios automatic-ref-counting

我想为一个dealloc方法编写iOS单元测试,该方法(基本上)将对象作为另一个对象的委托删除.

- (void) dealloc {
    someObject.delegate = nil;
}
Run Code Online (Sandbox Code Playgroud)

但是,dealloc在使用ARC时我无法直接呼叫.编写单元测试的最佳方法是什么?

das*_*ght 6

将实例分配给弱变量:

MyType* __weak zzz = [[MyType alloc] init];
Run Code Online (Sandbox Code Playgroud)

该实例将立即解除分配.

或者,您可以在单元测试文件上禁用ARC并调用dealloc.


7yn*_*k3r 5

更好的解决方案很简单

- (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);
}
Run Code Online (Sandbox Code Playgroud)

这可以为我们想要在内部解除分配的类创建一个实例,@autorealase一旦我们退出块就会释放(如果我们没有泄漏).weakReference将保留对实例的引用而不保留它,将被设置为nil.