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:
- Why does ref count goes to 3 when using the getter accessor of Rectangle’s origin? Am I doing something wrong ?
- 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!
Because your @property is declared as
atomic(the default) and, thus, the synthesized getter retains and then autoreleases the return value.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.
An
autoreleaseis simply a delayedreleasethat kicks in when the containing pool isdrained. So, in your case, the object will be deallocated when[pool drain];is executed.