Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if I have a pointer to released object?

In a function I am processing an object which may be corrupted sometimes, at runtime, can I somehow determine whether or not my object is corrupted?

like image 838
user192313 Avatar asked Sep 06 '25 03:09

user192313


1 Answers

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

like image 69
Richard J. Ross III Avatar answered Sep 07 '25 19:09

Richard J. Ross III