The only way to really do this is to leverage a new thing with ARC (and iOS 5, doesn't work before this) called __weak
pointers.
It should also be noted that __weak
variables do not retain, by definition. If a __weak
variable retained it's target, then by definition, it couldn't release itself.
Basically, a __weak
pointer is a variable that automatically set's itself to NULL
when it is deallocated. Thus, you can do something like this to determine if an object is deallocated:
__strong id object; // required so that the object doesn't get deallocated right away
__weak id _weakRef;
object = [NSObject new];
_weakRef = object;
// do stuff with 'object'
if (_weakRef)
{
// 'object' hasn't been deallocated yet, do something with it.
}
Normally speaking, you don't hold onto a strong and weak reference to an object, however, as this causes _weakRef
to be useless (just check when you set object
to nil
).
I would also caution against having a design pattern based solely on __weak
variables, especially if you are making a framework. Nothing says 'Annoying' like having to use iOS 5 as your target deployment.
I hope this post helped you get a deeper understanding of how weak references work, and if not, there is an excellent wikipedia article you can read here:
http://en.wikipedia.org/wiki/Weak_reference
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…