Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The method <code>getFoo</code> doesn't return an object with a 0 retain count. It returns an object with a <strong>+0 retain count</strong> which means that:</p> <ul> <li>the object's retain count is not null (otherwise, the object wouldn't exist)</li> <li>and the retain count wasn't altered by the invocation of the method, or if it was, it was in a balanced way (with as many <code>release</code>/<code>autorelease</code> as <code>retain</code>/<code>alloc</code>/<code>new</code>/<code>copy</code>).</li> </ul> <p>Thus the lifetime of the object entirely depends on where and how it is retained. We don't know how long the object will be valid as any method invocation <em>could</em> release the object.</p> <p>For example, let's consider the following code:</p> <pre>id anObject = [anArray objectAtIndex:0]; [anArray removeObjectAtIndex:0];</pre> <p>The object <code>anObject</code> isn't retained any more by the array as we removed it. Therefore it may have been destructed (but maybe it wasn't because it is still used somewhere else).</p> <p>Generally, when getting an object from a method (other that <code>alloc</code>, <code>copy</code>, <code>new</code> or <code>retain</code>), we can assume that:</p> <ul> <li>either the object was retained then autoreleased,</li> <li>either the object is retained by the object that returned it.</li> </ul> <p>So we know the object <code>foo</code> is valid until we return from the current method/function or we invoke a method/function that alter the state of the object <code>bar</code>, whichever comes first. After that, it may have been destructed.</p> <p>So in your case, you can safely omit the <code>retain</code>/<code>release</code> pair.</p> <p>However, it is very difficult to guaranty that an object doesn't get released unless we know the implementation of every method we invoke. Therefore, retaining (then releasing) every single object we get is the safer approach and that's what the compiler will do when you enable ARC (Automatic Reference Counting).</p> <p>But that would require you to write a lot of <code>retain</code>/<code>release</code> and your code would become difficult to read, understand and maintain. Moreover, the more code you write, the more bugs you get (unless you never write bugs).</p> <p>In conclusion, you don't need to retain an object unless you have a reason to suspect it could vanish otherwise.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload