title: NSOperation: addsubview in the main thread and slowness
body: <p>I have implemented the following NSOperation, to draw <code>N</code> custom views</p>
  
  <pre><code>- (void)main {
  
      for (int i=0; i&lt;N; i++) {
  
         &lt;&lt; Alloc and configure customView #i &gt;&gt;
         //(customView is a UIView with some drawing code in drawrect)
  
         [delegate.view addSubview:customView];
  
      }
  
      NSLog(@"Operation completed");
  }
  </code></pre>
  
  <p>in the drawRect method of the customView I have </p>
  
  <pre><code>- (void)drawRect {
  
      &lt;&lt;Drawing code&gt;&gt;
  
      NSLog(@"Drawed");
      delegate.drawedViews++;
  
      if (delegate.drawedViews==VIEWS_NUMBER) {
          [delegate allViewsDrawn];
      }
  }
  </code></pre>
  
  <p>So the delegate get the notification when all the views are drawn. </p>
  
  <p><strong>The problem is that after the "Operation completed" log it takes about 5 seconds before I can see the first "Drawed" log.</strong></p>
  
  <p><strong>Why is this happening? And generally speaking, how should I behave in order to find out which line of code is taking so much time being executed?</strong> </p>
  
  <p>------ EDIT ------</p>
  
  <p>Sometimes (like 1 out of 10 times) I was getting crashes doing this because I shouldn't call <code>addsubview</code> from the NSOperation since it is not thread-safe. So I changed it to:</p>
  
  <pre><code>[delegate.view  performSelectorOnMainThread:@selector(addSubview:) withObject:customView waitUntilDone:NO];
  </code></pre>
  
  <p>Now I don't have crashes anymore, but the process takes a very long time to be executed! Like 5 times more than before.</p>
  
  <p><strong>Why is it so slow?</strong></p>