views:

240

answers:

4

What's the proper way to tell if an object is allocated in Objective-C?

I've seen in sample code (and this seems to work only if it's never been allocated):

if(!Object) { ... }

I've also tried setting Object = nil, but that's a tedious process each time, gets a little bit annoying.

But if I have an object, and I want to allocate and release it more than once, what's the proper way? Thanks!

+3  A: 

There is no way to tell whether a variable points to a valid object aside from simply sending it a message and seeing if you crash. Object variables are just pointers. The only way to tell is to use a sentinel value (such as nil). But that shouldn't generally be a problem. If this is giving you trouble, that's evidence of a flaw in your application's design. There's no reason to have variables hanging around that might be initialized or might not.

Chuck
You can declare variables that don't point to things, but there shouldn't be situations where you don't know if they point to something or not. You can just declare a pointer and not set it, doing so later, but you should know it its set +! :D
CrazyJugglerDrummer
+3  A: 

You should always initialize object variables to nil if you're not immediately assigning them a value. Not doing so is virtually guaranteed to cause a crash at some point when you try to access an uninitialized object.

Then you can indeed do

if(!object)
{
    //some stuff
}

because a nil object is guaranteed to return a negative boolean result, and any object that is not nil will return a positive result.

Rob Keniger
Static, global and instance variables are always initialized to nil; reinitializing them would be redundant. (setting them back to nil after one has released their contents, however, is a must (except in dealloc of course))
rpetrich
A: 

Another option is to look into NSZombie. It can help you identify zombies (pointers that reference memory locations that have been deallocated (and possibly reallocated to something else!)), but you wouldn't want it in production code.

Depending on the complexity of your situation, you'll either need to set the variable to nil right after you release it, or you'll need to create another variable to track references yourself. But all of this is just asking for trouble.

If you're really stuck and the object variable is referenced by something that won't be released until after you're done with the object, then just put the object in the autorelease pool and be done with it.

Gordon Worley
A: 

The current best practice with properties is to send the setter method nil. So something like @property (nonatomic, retain) UIButton *startButton; is relesed with self.startButton = nil; This only works with read-write properties. With read only properties or instances with out setters you have to set them to nil after releasing them.

seano1