I've people who use [variable release]
and some other times variable = nil
to clean up memory?
When do you use each one? and what are the differences?
I've people who use [variable release]
and some other times variable = nil
to clean up memory?
When do you use each one? and what are the differences?
variable = nil;
will not release memory. self.property = nil;
will release memory if [self setProperty:nil];
would, for example a synthesized property with the retain attribute. Calling [variable release];
will always release one reference of an object.
Depends on what you mean by "clean up memory".
release
is the only thing that frees dynamically allocated memory allocated by alloc
. alloc
should always be paired with a call to release
or autorelease
somewhere.
Setting a varible to nil
does not necessarily free any memory (see drawnonward's answer), and can be a source of memory leaks.
When you see a variable set to nil
, it's about preventing it from accidentally being used later after its memory has been freed (this can cause crashes). While you can always set a variable to nil
after a call to release
, it's somewhat a matter of style when it's actually necessary. For example, you don't often see variables set to nil
in the dealloc
method of a class, since by that point an object won't be able to accidentally misuse such a variable anymore, since it's being nuked.
If a property is set to retain
, then these 3 are equivalent:
[self setProperty:nil];
self.property = nil;
[property release]; property = nil;
In each case, the object will be released, and then set to nil so that all access to the object from then on will not be allowed. "nilling" the instance variable is handy since it ensures you can only ever release the object once in this context because calling self.property = nil
twice will do nothing the second time, but calling [property release]
will release the object twice even though you likely only retain it once.
Most of the time I find it least bug prone to let retain properties do their thing and try to stay away from explicit retain
and release
calls most of the time.