user192313
user192313

Reputation: 69

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?

Upvotes: 4

Views: 2103

Answers (3)

justin
justin

Reputation: 104698

Assuming that object is an NSObject, just enable Zombies in Instruments. Then all you have to do is message the object in question. It will let you know if the object is dead when you message it.

Upvotes: 0

Richard J. Ross III
Richard J. Ross III

Reputation: 55543

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

Upvotes: 7

highlycaffeinated
highlycaffeinated

Reputation: 19867

Short answer, no, there's no way to tell if your object has been deallocated. For more explanation, check out this question.

Upvotes: 0

Related Questions