tags:

views:

365

answers:

4

After releasing objects is it best to set the pointers to nil? Thats what I have been doing, just wanted to ask if its necessary, good practice or overkill?

- (void)dealloc{
    [planetName release]; // NSString instance variable
    [super dealloc];
}
@end

.

- (void)dealloc{
    [planetName release]; // NSString instance variable
    planetName = nil;
    [super dealloc];
}
@end

cheers -gary-

+1  A: 

Exact duplicate:

Is It Necessary to Set Pointers to nil in Objective-C After release?

James
Quite true, although the accepted answer here also has some value and merit of its own.
Quinn Taylor
A: 

It's considered good practice. If you set your pointers to nil after releasing them, then in case you misuse your variable at a later point of execution, you'll get a proper error.

Pablo Santa Cruz
+1  A: 

Usually when programming in C/C++ I set it to null. Why, because even if you free the memory being pointed, the pointer still holds the address of that freed memory. It can cause a serious access violation problems in code like this:

if(myPointer != null) { doSomething(myPointer); }

If you had set your pointer to null, this will never happen

Andres
+5  A: 

Depends on the scope of the variable that holds the pointer. I always set pointers to nil if they continue to exist within the scope, just in case I'm calling the variable again somewhere else. Otherwise, there's a risk that I would access a memory location that contained an object which is now released.

But if the variable goes out of scope, then it won't be used either, thus assigning nil to it is a bit overkill. Still, it is a good practice to just assign nil just in case someone else decides to add code to your code and accidently uses the variable again within it's scope but after it was freed.

Workshop Alex
thank you, much appreciated.
fuzzygoat