Under ARC, I have an object, Child that has a weak property, parent. I'm trying to write some tests for Child, and I'm mocking its parent property using OCMock.
Under ARC, setting an NSProxy subclass using a synthesized weak property setter doesn't set the property ... the line after the weak property is set, checking it reveals that it's already nil. Here's the concrete example:
@interface Child : NSObject
@property (nonatomic, weak) id <ParentInterface>parent;
@end
@implementation Child
@synthesize parent = parent_;
@end
// ... later, inside a test class ...
- (void)testParentExists
{
// `mockForProtocol` returns an `NSProxy` subclass
//
OCMockObject *aParent = [OCMockObject mockForProtocol:@protocol(ParentInterface)];
assertThat(aParent, notNilValue());
// `Child` is the class under test
//
Child *child = [[Child alloc] init];
assertThat(child, notNilValue());
assertThat(child.parent, nilValue());
child.parent = (id<ParentInterface>)aParent;
assertThat([child parent], notNilValue()); // <-- This assertion fails
[aParent self]; // <-- Added this reference just to ensure `aParent` was valid until the end of the test.
}
I know that I can get around this using an assign property instead of a weak property for the Child to reference the Parent, but then I'd have to nil out the parent when I was done with it (like some sort of caveman), which is exactly the sort of thing that ARC was supposed to obviate.
Any suggestions on how to make this test pass without changing my app code?
Edit: It seems to have to do with OCMockObject being an NSProxy, if I make aParent be an instance of NSObject, the child.parent weak reference "holds" a non-nil value. Still looking for a way to make this test pass without changing app code.
Edit 2: After accepting Blake's answer, I did an implementation in my project of a preprocessor macro that conditionally changed my properties from weak -> assign. Your mileage may vary:
#if __has_feature(objc_arc)
#define BBE_WEAK_PROPERTY(type, name) @property (weak, nonatomic) type name
#else
#define BBE_WEAK_PROPERTY(type, name) @property (assign, nonatomic) type name
#endif