views:

94

answers:

2

Regarding over-releasing. Say I have a instance variable defined in Test.h

NSString *mystring;

In my implementation Test.m I do not initialize the variable mystring anywhere. But I release it in dealloc:

-(void)dealloc {
    [mystring release];
}

Is this now over-released? I've been doing the following in dealloc to avoid any issues, however, is this really necessary?

-(void)dealloc {
     if (mystring) [mystring release];
}

It seems that [nil release] shouldn't do anything, can someone verify this with class members?

+3  A: 

There is no way to over-release something that never existed in the first place.

Instance variables are initialized to nil and, thus, [mystring release] is messaging nil which is just fine in Objective-C.

Your -dealloc methods do need to call [super dealloc] at the end, though.

bbum
Ok great, sounds like I've been doing redundant checks.
Dude Man
A: 

First, why are you creating a variable at the class level that you're not initializing anywhere?

As this post is tagged iphone and it's IMPORTANT to manage your memory in the iphone environment it's always a good idea to release something if you've defined even if you don't assign it.

You can call release on an uninitialized variable without any problems, and be sure to [super dealloc]

Matt S
For the sake of making the question simple. But, assume I have initialized mystring and released it somewhere else in the code, are there issues with calling release in dealloc without verifying it's not nil?
Dude Man
Matt S
You can release an uninitialised instance variable to your hearts content because it's not really an uninitialised variable - it's initialised to 0 by the runtime. You cannot release an uninitialised variable if it's a local variable in a method or function.
JeremyP