【发布时间】:2014-09-22 15:54:23
【问题描述】:
我遇到了一个问题,即在块中捕获的对象似乎没有被释放,即使对对象和块的所有引用都已设置为 nil。
为了说明这个问题,我整理了这个非常简单的单元测试,应该通过但没有:
/* Headers */
@interface BlockTestTests : XCTestCase
@end
// A simple class that calls a callback when it's deallocated
@interface Dummy : NSObject
@property (nonatomic, copy) void(^deallocCallback)();
@end
/* Implementation */
@implementation BlockTestTests
- (void)testExample {
XCTestExpectation *exp = [self expectationWithDescription:@"strong reference should be deallocated when its capturing block is released"];
Dummy *dummy = [Dummy new];
dummy.deallocCallback = ^{
[exp fulfill];
};
void(^capturingBlock)() = ^{
// Captures a strong reference to the dummy
id capturedStrongReference = dummy;
};
capturingBlock = nil;
dummy = nil;
// At this point we would expect that all references to the
// object have been cleared and it should get deallocated.
// Just to be safe, we even wait 2 seconds, but it never happens...
[self waitForExpectationsWithTimeout:2.0 handler:nil];
}
@end
@implementation Dummy
- (void)dealloc {
_deallocCallback();
}
@end
你能告诉我为什么这个测试失败了吗?
【问题讨论】:
标签: objective-c unit-testing objective-c-blocks xctest