title: How to properly open and close a NSStream on another thread
body: <p>I have an application that connects to a server using NSStream on another thread. The application also closes the connection should the user decide to log out. The problem is that I am never able to successfully close the stream or the thread upon having the user disconnect. Below is my code sample on how I approach creating a thread for my network and trying to close the stream:</p>
  
  <pre><code>+ (NSThread*)networkThread
  {
      static NSThread *networkThread = nil;
      static dispatch_once_t onceToken;
      dispatch_once(&amp;onceToken, ^{
          networkThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkThreadMain:) object:nil];
  
          [networkThread start];
      });
  
      return networkThread;
  }
  
  + (void)networkThreadMain:(id)sender
  {
      while (YES)
      {
          @autoreleasepool {
              [[NSRunLoop currentRunLoop] run];
          }
      }
  }
  
  - (void)scheduleInThread:(id)sender
  {
      [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
      [inputStream open];
  }
  
  - (void)closeThread
  {    
      [inputStream close];
      [inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
      [inputStream release];
      inputStream = nil;
  }
  </code></pre>
  
  <p>Call made when trying to connect the inputstream:</p>
  
  <pre><code>[self performSelector:@selector(scheduleInThread:) onThread:[[self class] networkThread] withObject:nil waitUntilDone:YES];
  </code></pre>
  
  <p>Any advice is greatly appreciated.</p>