title: How to manage the autorelease pool of a NSRunLoop running in a secondary thread?
body: <p>In Apple's <a href="http://developer.apple.com/library/ios/#samplecode/MVCNetworking/Introduction/Intro.html" rel="nofollow">MVCNetworking</a> sample code, the <code>NetworkManager</code> class includes this method to maintain a run loop in a secondary thread dedicated to network activity (in order to run <code>NSURLConnection</code> asynchronously):</p>
  
  <pre><code>- (void)networkRunLoopThreadEntry
  {
      while(YES) {
          NSAutoreleasePool *pool;
          pool = [[NSAutorelease alloc] init];
          [[NSRunLoop currentRunLoop] run];
          [pool drain];
      }
  }
  </code></pre>
  
  <p>Since the <code>run</code> method exits immediately if there is no source attached to the run loop, this looks like an infinite <code>while</code> loop which is going uselessly to consume CPU resources  if there is currently no NSURLConnection attached to the run loop.</p>
  
  <p>On the other hand, to keep the run loop active, <a href="http://macsamurai.blogspot.fr/2008/03/nsoperation-madness.html" rel="nofollow">some</a> <a href="http://www.cocoaintheshell.com/2011/04/nsurlconnection-synchronous-asynchronous/" rel="nofollow">suggests</a> to schedule an empty port in the run loop: </p>
  
  <pre><code> - (void)networkRunLoopThreadEntry
   {
       NSAutoreleasePool *pool = [[NSAutorelease alloc] init];
       NSPort *port = [NSPort port];
       [[NSRunLoop currentRunLoop] addPort:port forMode:NSRunLoopCommonModes];
       [NSRunLoop run];
       [pool drain];
   }
  </code></pre>
  
  <p>However, in this case, my worry is that the <code>run</code> method will never exit, which means the pool will never get drained, which means all objects allocated and autoreleased in the secondary thread will leak.</p>
  
  <p>What is the way to go then?</p>
  
  <p>(For the context, as many others, I'm trying to encapsulate an asynchronous <code>NSURLConnection</code> inside a <code>NSOperation</code>, which means it can be triggered outside of the main thread. Also, the MVCNetworking sample code, as well as the WWDC 2010 sessions <em>Network Apps for iPhone OS</em>, seem to suggest it is a good idea to have a unique secondary thread dedicated to network transfers to prevent latency on the main thread.) </p>