Joris Kluivers

I like to build software.

Weak References to NSProxy With ARC

The common pattern to declare delegates when using ARC is using a weak ownership:

1
2
3
@interface MyObject
@property(nonatomic, weak) id<MyObjectDelegate> delegate;
@end

However using a weak delegate this way recently failed without apparent reason:

1
2
3
4
myObject.delegate = aDelegate;
// delegate property is still nil
NSLog(@"myObject.delegate: %@", myObject.delegate);
// Logged: 'myObject.delegate: (null)'

I was testing my class using OCMock and used +[OCMockObject mockForProtocol:] to create my delegate. Turns out OCMock is creating mocked objects as NSProxy subclasses, and ARC has issues with weak references to proxies.

More people with the same issues when using OCMock and ARC narrowed this problem down.

I created my own bare minimum project as a demonstration of the issue. A bug has also been filed know as rdar://11117786 (mirrored at openradar).