The basic rule that I have been going by is "if I alloc, I dealloc," but is this an overly simple view?
Asked
Active
Viewed 594 times
4
-
Note that this is also [answered here](http://stackoverflow.com/questions/3256926/objective-c-do-you-have-to-dealloc-property-objects-before-deallocating-the-pare/3256948#3256948). – Chris Frederick Jul 04 '11 at 21:28
2 Answers
13
The rule is "if you invoke a method that starts with new
or alloc
, is called retain
, or contains copy
, then you must (auto)release
". (Easy way to remember this is the acronym: "NARC")
If you declare a @property
as (retain)
or (copy)
, then you are responsible for the backed object, and you must do:
[myProperty release];
in your dealloc
method.

Dave DeLong
- 242,470
- 58
- 448
- 498
-
Obligatory link to the complete rules: http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/ – Peter Hosey Oct 03 '10 at 22:35
-
3@jeff the modern runtime synthesizes ivars, which means you can still use the ivar directly in the code even though you never declared it. :) – Dave DeLong Oct 03 '10 at 22:58
-
@Dave - that last comment is what threw me, i think. I started coding with that behavior and didn't think about it until recently. (ivars being synthesized) after some time away from Obj-c, I am in the habit of giving instance variables a different first letter. Thank you. – griotspeak Oct 04 '10 at 00:44
-
Hmmm, as far as I was aware, the synthesized ivars needs to be accessed via the "->" operator, which is unnatural for Cocoa programmers. ie, [self->myProperty release]. – Jeff Oct 07 '10 at 02:19
-
1Even if it works, its documented not to. http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html. Quote: If you are using the modern runtime and synthesizing the instance variable, however, you cannot access the instance variable directly, so you must invoke the accessor method. – Jeff Oct 10 '10 at 23:00
-
@Jeff I humbly submit to the documentation. You apparently should not use synthesized ivars in `-dealloc` whether or not you *can*. – Dave DeLong Oct 11 '10 at 00:34
1
Rule of the thumb: (Almost) never call dealloc
directly, use release
instead. There are some exceptions. For example, in your object's dealloc
method you should call [super dealloc]
.

Mustafa
- 996
- 1
- 9
- 18