Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the need of assigning 'nil' after releasing an object

I usually release the object after use by

[myObject release];

But I found in some online tutorials that they assign a nil after releasing the object. Like

[myObject release];
myObject = nil;

Is it required?

like image 204
Aaron Avatar asked Feb 14 '12 11:02

Aaron


2 Answers

It's a long-running debate as to whether setting the pointer to nil after releasing is necessary, but I come down on the side of it being a good idea.

After the object is released, the pointer you hold to it still points to the same place. If your release has taken the retain count to 0 then the object will be deallocated. If you then try and send a message to the deallocated object you'll get an EXC_BAD_ACCESS error. However, sending a message to the pointer after it's been set to nil won't error - it just won't do anything.

The other side of the argument is that if you're messaging a deallocated object it's good to know about it and fix your code to make sure it doesn't happen.

There are smart people in both camps.

like image 194
marramgrass Avatar answered Nov 07 '22 08:11

marramgrass


No, it is not strictly required.
If your code is well-structured there's no need to force myObject to be equal to nil.

However it may be a good habit: release does not immediately destroy the object, just decrease the retain count. Thus it may be,that, even if you call release, the object will still be there for a while, creating problems if you try to send it messages.

Using myObject = nil; eliminate this problem, since, even if you send a message to myObject nothing will actually happen.

like image 24
Manlio Avatar answered Nov 07 '22 06:11

Manlio