I am presenting an important limitation of one of the earlier answers, along with an explanation and an improvement.
Johnmph suggested using [NSValue valueWithNonretainedObject:]
.
Note that when you do this, your reference acts not like __weak
, but rather like __unsafe_unretained
while inside the NSValue object. More specifically, when you try to get your reference back (using [myNSValue nonretainedObjectValue]), your application will crash with an EXC_BAD_ACCESS signal if the object has been deallocated before that time!
In other words, the weak reference is not automatically set to nil while inside the NSValue
object. This took me a bunch of hours to figure out. I have worked around this by creating a simple class with only a weak ref property.
More beautifully, by using NSProxy
, we can treat the wrapper object entirely as if it is the contained object itself!
// WeakRef.h
@interface WeakRef : NSProxy
@property (weak) id ref;
- (id)initWithObject:(id)object;
@end
// WeakRef.m
@implementation WeakRef
- (id)initWithObject:(id)object
{
self.ref = object;
return self;
}
- (void)forwardInvocation:(NSInvocation *)invocation
{
invocation.target = self.ref;
[invocation invoke];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
return [self.ref methodSignatureForSelector:sel];
}
@end