views:

594

answers:

1

Hello,

I have been developing with objective C and the Cocoa framework for quite some time now. However it is still not absolutely clear to me, when am I supposed to set object references to nil. I know it is recommended to do so right before releasing an object that has a delegate and you should also do so in the viewDidUnload method for retained subviews. But exactly when should this be done and why?. What does it accomplish exactly?. Thank you in advance.

-Oscar

+17  A: 

Say you have a pointer myView defined in your class' interface:

@interface MyClass {
   UIView *myView;
}

@end

Then in your code, at some point, you may release that variable:

[myView release];

After you do that, myView, the pointer, won't be pointing to nil, but will be pointing to a memory address of an object that may not exist anymore (since you just released it). So, if you happen to do something after this, like:

[myView addSubview:otherView];

you'll get an error.

If, on the other hand, you do this:

[myView release];
myView = nil;
...
[myView addSubview:otherView];

the call to addSubview will not have any negative impact, since messages to nil are ignored.

As a corollary, you may see suggestions of using retain properties, such as:

@property(retain) UIView *myView;

and then in the code, just do:

self.myView = nil;

By doing that, the synthesized accessor will release the old object and set the reference to nil in one line of code. This may prove useful if you want to make sure all your properties are both released and set to nil.

One thing that you must never forget, is that memory management is done by means of retain release calls, and not by means of assigning nil. If you have an object with a retain count of 1, and assign nil to it's sole variable, you'll be leaking memory:

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,10,10)];
view = nil;
// You just leaked a UIView instance!!!
pgb
Every aspiring Cocoa programmer should read this. I've read Kochan, Hillegass, and Apple's docs, and it still took me almost 6 months to understand some of the concepts pgb explained here. It seems obvious to me now, but it certainly wasn't before. vote++
refulgentis
Great answer!!!. Thank you so much.
OscarMk