title: Objective-C autorelease memory management
body: <p>Im trying to understand when to call autorelease, and what this will actually do to my object.</p>
  
  <p>After reading <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html)" rel="noreferrer"><em>About Memory Management</em></a> in the Mac Developer Library I understood that when you have a method that acts as a factory method - by creating a new object and returning it - the method has no way of releasing the object before returning it, because this would result in a deallocted object being returned.</p>
  
  <p><strong>Example</strong></p>
  
  <pre><code>- (Test *) createNewTest 
  {
      Test *newInstance = [[Test alloc] init];
      [newInstance release];
      return newInstance; // deallocted object returned.
  }
  </code></pre>
  
  <p>Instead I should use <code>autorelease</code>:</p>
  
  <blockquote>
    <p>The autorelease method, defined by NSObject, marks the receiver for later release</p>
  </blockquote>
  
  <p>My question is: if the object is to be released later, how do I know when its being released?</p>
  
  <pre><code>- (Test *) createNewTest 
  {
      Test *newInstance = [[test alloc] init];
      [newInstance autorelease];
      return newInstance;
  }
  
  - (void) runIt
  {
      Test *myInstance = [self createNewTest];
      // when is myInstance released?? and thereby not valid to my function anymore?
  }
  </code></pre>
  
  <p>How can I safely use the returned autoreleased object inside my <code>runIt</code> method if I don't know when the autorelease happens? Should I retain the object returned by the <code>createNewTest</code>? Or can I safely use it within the <code>runIt</code> scope? </p>