ADC Home > Reference Library > Technical Q&As > Carbon > Graphics & Imaging >


Q: What is QDSwapPort and why would I use it?

A: Before Mac OS X, setting the current port was an inexpensive operation that only involved a simple memory access. On Mac OS X, setting the port always involves a function call and potentially accesses per-thread globals, so there may be a non-negligible cost associated with the change. See Listing 1 for an example of setting the port the traditional way.

//    Changing ports without QDSwapPort
CGrafPtr savePort;
GetPort( &savePort );
SetPort( newPort );

//  Draw into the new port here

SetPort( savePort );

Listing 1. Old-style QuickDraw port manipulation

Introduced in Mac OS X 10.1, QDSwapPort records the old port, changes to the new port (if necessary), and returns whether or not the port actually changed. This allows you to save an extra SetPort call to restore the previous port if newPort and savePort are the same. Also, one QDSwapPort call is always faster than the pair of calls (GetPort and SetPort) which it replaces.

Note that you can pass NULL for the second parameter if you don't care about the previous port.

See Listing 2 for the suggested usage.

//    Changing ports with QDSwapPort
CGrafPtr savePort;
Boolean portChanged = QDSwapPort(newPort, &savePort);

//  Draw into the new port here

if (portChanged)
    QDSwapPort(savePort, NULL);

Listing 2. Port manipulation using QDSwapPort

[Nov 06 2002]

Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.