Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set pointers to nil after release?

Tags:

objective-c

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-

like image 420
fuzzygoat Avatar asked Sep 13 '09 22:09

fuzzygoat


3 Answers

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.

like image 164
Wim ten Brink Avatar answered Nov 08 '22 18:11

Wim ten Brink


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

like image 43
Andres Avatar answered Nov 08 '22 17:11

Andres


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.

like image 36
Pablo Santa Cruz Avatar answered Nov 08 '22 19:11

Pablo Santa Cruz