为什么我的单元测试中我的对象的弱委托属性为零? [英] Why is my object's weak delegate property nil in my unit tests?
问题描述
我有一个非常简单的单元测试设置。我有一个具有委托属性的类:
I have a pretty simple setup for this unit test. I have a class that has a delegate property:
@interface MyClass : NSObject
...
@property (nonatomic, weak) id<MyDelegateProtocol> connectionDelegate;
...
@end
我在我的测试中设置了委托:
and I set the delegate in my test:
- (void)testMyMethod_WithDelegate {
id delegate = mockDelegateHelper(); // uses OCMock to create a mock object
[[delegate expect] someMethod];
myClassIvar.connectionDelegate = delegate;
[myClass someOtherMethod];
STAssertNoThrow([delegate verify], @"should have called someMethod on delegate.");
}
但代表实际上并未设置在我的单元测试的第3行,所以永远不会调用#someMethod。当我将其更改为
But the delegate is not actually set on line 3 of my unit test, so #someMethod is never called. When I change it to
myClassIvar.connectionDelegate = delegate;
STAssertNotNil(myClassIvar.connectionDelegate, @"delegate should not be nil");
它在那里失败了。我正在使用ARC,所以我的预感是弱房产被解除分配。果然,将其更改为 strong
会使 STAssertNotNil
通过。但是我不想和代表那样做,我不明白为什么这会对你有所作为。根据我的阅读,ARC中的所有本地引用都是 strong
,而 STAssertNotNil(委托)
通过。当局部变量中的同一对象不是时,为什么我的弱委托属性为nil?
it fails there. I'm using ARC, so my hunch was that the weak property was being deallocated. Sure enough, changing it to strong
makes the STAssertNotNil
pass. But I don't want to do that with a delegate, and I don't understand why that makes a difference here. From what I've read, all local references in ARC are strong
, and STAssertNotNil(delegate)
passes. Why is my weak delegate property nil when the same object in a local variable is not?
推荐答案
这是iOS中的一个错误运行。以下讨论有更多细节。简而言之,iOS ARC运行时似乎无法处理对代理的弱引用。 OSX运行时可以。
This is a bug in the iOS runtime. The following discussion has more detail. In a nutshell, the iOS ARC runtime can't seem to handle weak references to proxies. The OSX runtime can.
http://www.mulle-kybernetik.com/forum/viewtopic.php?f=4&t=252
据我所知,从讨论中已经向Apple提交了一份错误报告。如果有人对解决方法有明智的想法......
As far as I understand from the discussion a bug report has been filed with Apple. If anyone has a sensible idea for a workaround...
这篇关于为什么我的单元测试中我的对象的弱委托属性为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!