views:

93

answers:

2

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
Obligatory link to the complete rules: http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/
Peter Hosey
... unless you didn't actually provide a backed object, in which case you should: useself.myproperty = nil
Jeff
@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
@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
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
@Jeff try it. :)
Dave DeLong
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
@Jeff I humbly submit to the documentation. You apparently should not use synthesized ivars in `-dealloc` whether or not you *can*.
Dave DeLong
+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