views:

41

answers:

2

Hey guys, suppose the following code:

int main (int argc, const char * argv[]) 
{
//[...]
    Rectangle* myRect  = [[Rectangle alloc] init];

    Vector2* newOrigin = [[[Vector2 alloc] init] autorelease]; // ref count 1

    [newOrigin setX: 50.0f];
    [myRect setOrigin: newOrigin];    // ref count 2

    [myRect.origin setXY: 25.0f :100.0f]; // ref count goes to 3... why ?

    [myRect release];

    [pool drain];
    return 0;
}

Rectangle's origin is declared as a (retain) synthesized property. Just wondering 2 things:

  1. Why does ref count goes to 3 when using the getter accessor of Rectangle's origin? Am I doing something wrong ?
  2. With a ref count of 3, I don't understand how this snippet of code cannot leak. Calling release on myRect will make it go down to 2 since I call release on the origin in dealloc(). But then, when does autorelease take effect?

Thanks!

+5  A: 

Why does ref count goes to 3 when using the getter accessor of Rectangle's origin?

Because your @property is declared as atomic (the default) and, thus, the synthesized getter retains and then autoreleases the return value.

Am I doing something wrong ?

Yes. You are studying absolute retain counts.

The absolute retain counts of any object is quite thoroughly useless to consider. You only care about deltas; if you cause the retain count to increase, you must cause it to decrease.

With a ref count of 3, I don't understand how this snippet of code cannot leak. Calling release on myRect will make it go down to 2 since I call release on the origin in dealloc(). But then, when does autorelease take effect?

An autorelease is simply a delayed release that kicks in when the containing pool is drained. So, in your case, the object will be deallocated when [pool drain]; is executed.

bbum
Good info. Didn't know the getter called a retain/autorelease.Thanks a bunch!
turbovince
Happy to help...
bbum
+2  A: 

From Apple's documentation on -retainCount:

Important: This method is typically of no value in debugging memory management issues. Because any number of framework objects may have retained an object in order to hold references to it, while at the same time autorelease pools may be holding any number of deferred releases on an object, it is very unlikely that you can get useful information from this method.

Preston