The Wayback Machine - https://web.archive.org/web/20041010021459/http://developer.apple.com:80/qa/qa2004/qa1167.html
Apple Developer Connection
Member Login Log In | Not a Member? Contact ADC

Technical Q&A QA1167
Using Interface Builder's NSOpenGLView or Custom View objects for an OpenGL application

Q: Should I use Interface Builder's NSOpenGLView object or the Custom View object when I'm creating a window to draw into with OpenGL?

A: While either one can be used to draw with OpenGL, the Custom View offers greater flexibility for the application than the NSOpenGLView in the palette with a minor amount of additional setup. The current Interface Builder inspector for NSOpenGLView offers a limited set of pixel format attributes, so applications that require additional pixel format attributes should instead use the Custom View approach. For instance, double buffering is not currently available as a pixel format attribute in the NSOpenGLView inspector.

Note that if the view is created by dragging an NSOpenGLView out of the Graphics Views palette, the initialization routines initWithFrame: and initWithFrame: pixelFormat: are not called for the NSOpenGLView. In this case, setup and initialization code should go into the view's -awakeFromNib method, however any calls that require an active OpenGL context (such as most of the gl...() type calls) must be made after an OpenGL context has been created and made current. The first time through the -drawRect: method is a good place for this.

Listing 1: Sample setup for an NSOpenGLView

-(void)awakeFromNib
{
     // Create a basic pixel format for us to use
      NSOpenGLPIxelFormat pf = [NSOpenGLContext defaultPixelFormat];

     // Init with the superview's method
     self = [super initWithFrame:[self frame] pixelFormat:pf];

}

-(void)drawRect:(NSRect)rect
{
     // Set a variable to control our initialization code
     static BOOL readyToDraw = NO;

     // Check to see if we're initialized
    if(!readyToDraw)
    {
       // ... do some setup code here
       // we have a valid OpenGL context at this point

       // Make sure we set this so we don't reinitialize next time
       readyToDraw = YES;
    }

}

As an aside, an NSOpenGLContext can be attached to any NSView, so using an NSOpenGLView is not strictly required. NSOpenGLView is really just a lightweight subclass of NSView that provides some convenience methods for setting up OpenGL drawing. However, keep in mind that attaching an NSOpenGLContext to any view will override any Quartz drawing or other content that is present within its boundaries.

Document Revision History

DateNotes
2004-10-04First Version

Posted: 2004-10-04