Profo
Profo

Reputation: 153

Releasing objects

I release objects created by @property directive in dealloc method like this

-(void)dealloc
{
  [object release], object = nil;
}

I have two questions.

  1. Is dealloc method the right place for releasing object generated by @property ?
  2. Is it a good practice to set objects to nil ?

Upvotes: 0

Views: 73

Answers (2)

Eugene
Eugene

Reputation: 10045

Yes it is a good practice to set the pointer to direct to nil after releasing the object. The reason is that if you'd try to access value of that object in future after the object gets deallocated, you'll try to access a garbage value (it's called a dangling pointer) and your application would crash. But if the pointer is set to nil, then you can do anything with it, because you can send messages to nil objects.

To put your two lines of code into one, just use the accessor methods:

self.object = nil; //this will both release an object and set its pointer to nil

Upvotes: 1

mattjgalloway
mattjgalloway

Reputation: 34902

  1. It is the right place to be releasing the object. Obviously only if you're not compiling with ARC enabled though as with ARC you can't even call release anyway.

  2. There's no real point setting it to nil. It's about to be completely destroyed - why bother setting it to nil?

Upvotes: 0

Related Questions