iosobjective-cautomatic-ref-countingautoreleasereference-counting

Manual reference counting and AutoRelease


In manual memory management on what scenarios you will go for Auto Release

I'd like to be well prepared as I am about to do a project using without ARC


Solution

  • You typically use autorelease when you need to return an object from a method, and relinquish ownership at the same time: upon returning the calling side (not the creating method) should own the object.

    If you just relinquish ownership before returning the object (with release), it gets immediately deallocated and the calling side can not use it. If you don't call release, the object has a reference count of +1 from the called function (that instantiated it), which also has no further chance to release after the calling side has claimed ownership.

    So, autorelease is like a "deferred release": the object gets sent one release method at a later time (but not before the function that is returning it returns).


    Addendum:

    The alternative approach is to return objects with an agreed-upon reference count of 1, and rely on the calling side to release it when done.

    This is made explicit by adopting a preestablished naming pattern for those methods: In cocoa, they typically contain the words "alloc", "new", "copy" or "mutalbeCopy".

    Source: Apple's documentation.