views:

37

answers:

1

After reading the Memory Management Guide I am trying to get my head around what is happening here My understanding "so far" is ...

- (EngineClass *)engine {
    return [[engine retain] autorelease];
}
  1. I am returning a pointer to an Engine object.
  2. The retain count of the object is incremented to record we are making a new pointer to the object
  3. Balance the above retain by specifying an autorelease at some future point.

Am I on the right track?

cheers -gary-

+1  A: 

I'm not sure I'd say the retain is "to record we are making a new pointer to the object."

The retain-autorelease pair is there to indicate that there's another object interested in the return value, so it needs to stick around at least that long, but the other object doesn't properly own the return value. Without the retain, if the object performing this method is deallocated immediately afterward, the engine might not have any other owners and would also be deallocated immediately. That's not the expected behavior. Doing it this way causes the object's ownership not to go away until the autorelease pool is drained.

Chuck
Thank you, I see now, I was not thinking of retain-autorelease as a pair. Also I think I was getting mixed up, thinking in terms of incrementing the retain to show that a new object is now pointing at engine. I think I get it now.
fuzzygoat