Monday, October 15, 2012

When do you need to send AutoRelease message to an object

If the object is created with convenience method, like [NSMutableArray arrayWithCapacity], then the convenience constructor already sends the AutoRelease message to the object when it is created, so when the auto release pool or block is ended, it will send the release message to the object.

If the object is created with the alloc or copy constructor, and the object is returned to caller as a method return value or output parameter, then you should call AutoRelease message on the object. The reason is the receiver does not create the object, so he is not the own of the object and is not responsible to release the object. While after the object is returned by the method, then the creator of the object lose the control of the object and cannot actively release the object. The only limited control the original creator has on the object is sending autorelease message to it before relinquishing the control of the object, and that will be sure the object gets released sometime when the autorelease pool is closed.

However, in both cases, if the autoreleased object is created on a long-living auto release pool, then the object will last for long time and that will cause the object dose not be released quickly.

No comments:

Post a Comment