The basic rule that I have been going by is "if I alloc, I dealloc," but is this an overly simple view?
+12
A:
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
2010-10-03 22:08:59
Obligatory link to the complete rules: http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/
Peter Hosey
2010-10-03 22:35:15
... unless you didn't actually provide a backed object, in which case you should: useself.myproperty = nil
Jeff
2010-10-03 22:56:33
@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
2010-10-03 22:58:54
@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
2010-10-04 00:44:02
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
2010-10-07 02:19:15
@Jeff try it. :)
Dave DeLong
2010-10-07 02:58:45
Even 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
2010-10-10 23:00:40
@Jeff I humbly submit to the documentation. You apparently should not use synthesized ivars in `-dealloc` whether or not you *can*.
Dave DeLong
2010-10-11 00:34:06
+1
A:
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
2010-10-03 22:41:11