简体   繁体   中英

Objective-C object allocated

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!

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM