Memory management question

Joined
Jun 16, 2009
Messages
1
Reaction score
0
Points
1
Having coded for many years in everything from Python to 6502 assembler, I'm finally learning Objective C.

Obviously, memory management is the big 'huh?' at the moment, so I was wondering if anyone had time to help me understand what's going on in the little code snippet below.

Given a class 'Head', and a class 'Human' defined elsewhere, I tried allocating a new Head for the Human in two different ways:

1) this is the way I like to code, but it leaves a permanently inflated retain count (as far as I can tell from my NSLog-ing):

human.head = [[Head alloc] init];

2) whereas this does not:

Head *head = [[Head alloc] init];
human.head = head;
[head release];


I'm well aware that there was no 'release' called in 1), but it seems odd if a one-line creation/assignment of this sort isn't treated as an auto-release.

Many thanks - especially if this is a really stupid question.
 
Joined
Jun 25, 2005
Messages
3,231
Reaction score
112
Points
63
Location
On the road
Your Mac's Specs
2011 MBP, i7, 16GB RAM, MBP 2.16Ghz Core Duo, 2GB ram, Dual 867Mhz MDD, 1.75GB ram, ATI 9800 Pro vid
The class methods alloc, copy, and new, create objects with a retain count of 1, not set for autorelease. In those cases, and where you explicitly perform a retain, you are responsible for performing a balanced release on an object. Since case one has no balanced release, you are leaking memory.

In case two you have balanced the retain count with a release, so things look good. I think though that if you refer to human.head after releasing head, you can end up crashing. The reason being that you simply assigned the ID (a pointer) from head to human head and they are both looking at the same object.

I've watched all of the Stanford iPhone classes that you can download via iTunes U and the memory discussion of interest to this question is class 3. The "Object Life Cycle" section starts at minute 19 at slide 18, which are also downloadable. Except for the specific iPhone items, the class is very applicable to OS X coding too.

When you receive an object via other means other than alloc, copy, and new, you are receiving and autorelease object. I don't know if there are any exceptions to this rule. If you want to keep it, you need to retain it, or copy it.

Apple has some information on the new garbage collection that arrived with Leopard; Objective-C 2.0 Overview, Introduction to Garbage Collection. As I understand it, you wouldn't have to worry about the retain stuff. I've also heard that there are or were some issues with some frameworks.
 

Shop Amazon


Shop for your Apple, Mac, iPhone and other computer products on Amazon.
We are a participant in the Amazon Services LLC Associates Program, an affiliate program designed to provide a means for us to earn fees by linking to Amazon and affiliated sites.
Top