Alex Rivera | Logout

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

Asked 2012-02-14T11:35:30.107
11

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?

Edit
Report

2 Answers

1

It is not required, but it is generally considered to be good practice in all environments, with the exception that it is generally considered unnecessary in a -dealloc method.

The reason it is common to set the object pointer to nil after release is because the Objective-C method dispatcher will not try to send a message to a nil object, which means that you're safe to accidentally use the object later.

answered 2012-02-14T11:42:14.490
-2

At an Apple Tech Talk I went to a couple of years ago the Apple engineers discussed a few instances where it was essential to assign to nil, but I can't recall the details other than it was inside dealloc in the instances discussed. Suffice it to say that it's not correct to say that you never have to or that it's bad-practice to do so. Sometimes you have to. But most times you don't have to. Sorry my memory isn't clearer.

answered 2012-02-14T11:50:51.417

Your Answer