Chiron
Chiron

Reputation: 20245

Why setting to nil after releasing?

I came across this method:

-(void) someMethod {
    NSMutableArray *anArray = [[NSMutableArray alloc] init]; 
    // Do stuff with anArray ... 
    [anArray release];
    anArray = nil;
}

Is setting the array to nil necessary?
In this code by sending a release message to the array, it will causes the array to be deallocated.

Upvotes: 1

Views: 174

Answers (4)

JeremyP
JeremyP

Reputation: 86661

In this case, it is a pointless waste of key strokes because the variable anArray goes out of scope immediately.

In other cases, where the variable stays in scope for a while after you release the object its pointing to, it is a good idea, because, if you accidentally dereference it, you will get a EXC_BAD_ACCESS which is easy to spot, and if you send a message to it, it will be ignored (except for returning nil / 0).

Upvotes: 5

Wayne Hartman
Wayne Hartman

Reputation: 18487

As others have mentioned, setting it to nil will help your code not crash if you reference the dealloced object. If you reference a dealloced you will get EXC_BAD_ACCESS error and your app will crash. Since a nil object returns nil if a message is sent to it, your app will not crash.

In the example you provide, it is not necessary to nil it out, since it is contained in a method. However, you do not want to nil out a variable if you expect to use it somewhere else in the code, since the value will then be nil.

Upvotes: 4

BlueDog
BlueDog

Reputation: 976

It's not necessary but considered good behaviour to set dangling pointers to nil.

Upvotes: 0

Benoît
Benoît

Reputation: 7427

No it is not necessary.
It is just for safe reason (to not send a message to a zombie)
And you can test if your ivar is nil or not to realloc:

[ivar release];
ivar=nil;
...
if (ivar==nil) {
  ivar = [[NSObject alloc] init];
}
[ivar setValue:@"toto"];

Upvotes: 0

Related Questions