I present an important limitation of one of the early answers, as well as explanation and improvement.
Jonmf suggested using [NSValue valueWithNonretainedObject:] .
Note that when you do this, your link does not act as __weak , but rather as __unsafe_unretained , inside the NSValue object. More specifically, when you try to return your link (using [myNSValue nonretainedObjectValue]), your application will crash using the EXC_BAD_ACCESS signal if the object has been freed before this time!
In other words, a weak reference is not automatically set to zero while inside an NSValue object. It took me several hours to understand. I worked on this by creating a simple class with a weak ref value.
More beautifully, using NSProxy , we can fully process the wrapper object, as if it were 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
Timo Aug 06 '13 at 12:40 2013-08-06 12:40
source share