Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
965 views
in Technique[技术] by (71.8m points)

objective c - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...