views:

289

answers:

4

Example: I have a view controller and get rid of it. But there's still an variable holding it's memory address. Accessing that results in EXEC_BAD_ACCESS. Of course. But: Is there any way to check if that variable is still valid? i.e. if it's still pointing to something that exists in memory?

+2  A: 

That's what the entire memory management model is set up for - if you call retain at the right times, and release and autorelease at the right times, that can't happen. You can use NSZombie to help you debug.

Carl Norum
Yup, you shouldn't be having to check for this case, you should make sure that the objects are retained when you need them, and released when you don't.
Bearddo
A: 

If by variable, you mean whether the pointer to your object still references valid memory then:

MyClass *myVariable = [[MyClass alloc] init];

//Tons of stuff happens...

if (myVariable != nil) //Do more stuff

davecom
+18  A: 

You need to read this again:

Cocoa Memory Management Guidelines

In short, if you want something to stick around you must retain it.

If you want something to go away and you have previously retained it, you must release or autorelease it.

You must never call dealloc directly (except [super dealloc]; at the end of every one of your dealloc methods).

You must never release or autorelease an object that you did not retain.

Note that some methods do return retained objects that you must release. If you alloc an instance of a class, that implies a retain. If you copy and instance, the copy is retained.

If you are ever tempted to use the retainCount method, don't. It isn't useful. Only consider retain counts as a delta; if you add, you must subtract, but the absolute value is an implementation detail that should be ignored.

(In other words, even if there were ways to check for an object's validity definitively -- there aren't -- it would be the wrong answer.)

Oh, and use the Build and Analyze feature in Xcode. It does a very good -- but not quite perfect -- job of identifying memory management problems, amongst other things.

bbum
+1 Amen, reverend. This is the Gospel of Memory Management.
Dave DeLong
+1  A: 

Use "NSZombieEnabled" break point.

For this reason only all strongly recommend us to use accessors. If your object is released anywhere, it will get assigned to nil, and there will be no harm if you call any API or method on Nil object. So please make a habit of using Accessors.

you just add this NSZombieEnabled Flag as an argument to your application in build settings. and enable it. Now you run your application in debug mode. If any such crash is about to occur, this breakpoint will show you which object is freed and where it is crashing.

Cheers, Manjunath

Manjunath