The autorelease dance

March 13th, 2012

If you have ever seen the following pattern and wondered why:

NSObject *newObject = [[object retain] autorelease];

return newObject;

Well wonder no more!

The reason behind this retain/autorelease pattern is to ensure that the "object" will not be destroyed until the caller's autorelease pool drains so protecting the caller from other threads releasing the "object" in the middle of an access.

What do you think? Let me know by getting in touch on Twitter - @wibosco