title: Invalid context error from inside a drawRect member function
body: <p>While running an iOS program in XCode 4.6.3, I keep getting a long list of errors like the following:</p>
  
  <pre><code>Jul 20 13:24:40 ps2xipas3qfe Chess[277] &lt;Error&gt;: CGContextSetRGBFillColor: invalid context 0x0
  Jul 20 13:24:40 ps2xipas3qfe Chess[277] &lt;Error&gt;: CGContextFillRects: invalid context 0x0
  </code></pre>
  
  <p>Here is the code that generates the error:</p>
  
  <pre><code>- (void)drawRect: (CGRect)rect {
      //[super drawRect:rect];
      for(int i=0; i&lt;8; i++) {
          for(int j=0; j&lt;8; j++) {
              CGRect TheRect = CGRectMake(i*30+30,j*30+30,30,30);
              CGContextRef context = UIGraphicsGetCurrentContext();
              if(i%2 == j%2) {
                  CGContextSetRGBFillColor(context,1.0,0.0,0.0,0.0);
              }
              else {
                  CGContextSetRGBFillColor(context,0.0,0.0,0.0,0.0);
              }
              CGContextFillRect(context,TheRect);
          }
      }
  }
  </code></pre>
  
  <p>When I searched for the web for "invalid context" errors, the answers I got were that a graphics context can only be retrieved from within a "drawRect" member function, but this is within a "drawRect" function and I am still getting the error. The class here is <code>ChessBoard</code> which inherits from <code>UIView</code>.</p>
  
  <hr>
  
  <p>Thanks for the help, but I cannot get my program to run and am very confused. I no longer get the errors that I used to get, but I now only get a blank screen. I tried <code>setNeedsDisplay</code> and <code>setNeedsDisplayInRect</code> but neither of them seem to work.</p>
  
  <p>Here is a function I have in <code>ChessViewController.m</code>:</p>
  
  <pre><code>- (void)viewDidLoad
  {
      [super viewDidLoad];
      ChessBoard* TheBoard = [ChessBoard new];
      [self.view addSubview: TheBoard];
      // [TheBoard setNeedsDisplayInRect: CGRectMake(0,0,400,400)];
      [TheBoard setNeedsDisplay];
  }
  </code></pre>
  
  <p>Here is a function I have in <code>ChessBoard.m</code>:</p>
  
  <pre><code>- (void)drawRect: (CGRect)rect {
      [super drawRect:rect];
      UILabel* HelloWorld = [UILabel new];
      HelloWorld.text = @"Hello, World!";
      [HelloWorld sizeToFit];
      HelloWorld.frame = CGRectMake(1,1,100,20);
      [self addSubview:HelloWorld];
      for(int i=0; i&lt;8; i++) {
          for(int j=0; j&lt;8; j++) {
              CGRect TheRect = CGRectMake(i*30+30,j*30+30,30,30);
              CGContextRef context = UIGraphicsGetCurrentContext();
              CGContextFillRect(context,TheRect);
              if(i%2 == j%2) {
                  CGContextSetRGBFillColor(context,1.0,0.0,0.0,1.0);
              }
              else {
                  CGContextSetRGBFillColor(context,0.0,0.0,0.0,1.0);
              }
          }
      }
  }
  </code></pre>