Volume Number: 19 (2003)
Issue Number: 5
Column Tag: Programming
by Dave Mark
When I first started programming the Mac, lo those many years ago, one of the earliest programs I wrote was a teeny app called PictViewer. PictViewer put up a standard document window, with scroll bars and a grow box, and drew a pict image, centered in the window. The first version just displayed the image, clipping it to the window FrameRect as needed. The scroll bars were mere decoration. When I tackled a more advanced version of PictViewer, I added the callback routines and other code to bring the scroll bars to life. In still a later incarnation, I added the ability to drag and drop an image on a PictViewer window.
As I was putting the finishing touches on this project, I remember thinking, "gee, it sure would be nice if all this was just a bit easier." Frameworks like PowerPlant did go a long way towards stringing all the pieces together, but there was still a lot of hand-coding to be done and lots of room for error.
As you'll see in this month's program, TinyViewer, the combination of the Objective-C runtime and tools like Interface Builder and Project Builder take working with objects to the next level.
Getters, Setters, and Key Value Coding
Before we dig into TinyViewer, I'd like to take a moment to emphasize a point I made in my March column. The issue was a naming convention for accessor functions. I suggested that you name your getter methods to match the name of the instance variable being retrieved, then put the word "set" in front of that (be sure to cap the first letter after the word "set") to name the setter function. Here's the example I gave:
- (int)height; // Returns the value of the height field
- (void)setHeight:(int)h; // Sets the height field to
// the value in h
Bill Cheeseman, famous ex-attorney (remember the John Travolta movie A Civil Action? Bruce Norris played Bill in the movie. True.) and Cocoa aficionado (I highly recommend his most excellent book, Cocoa Recipes for Mac OS X: The Vermont Recipes), took the time to discuss the importance of this convention with me.
In a nutshell, consider this naming convention mandatory, not optional. In Bill's words:
"The -height and -setHeight: getter and setter naming conventions are expected by many features of the AppKit and Foundation. While these are optional naming "conventions" from the perspective of Objective-C as a language, they are effectively mandatory if you want to use the Cocoa frameworks. You will lose a lot of important Cocoa framework functionality if you don't follow these naming conventions.
The most important aspect of the Cocoa frameworks that depends on following these naming conventions is the key-value coding protocol. Look up key-value coding in the Cocoa documentation, and read the class reference document for the NSKeyValueCoding informal protocol in the Foundation frameworks. Several important Cocoa technologies use key-value coding, such as AppleScript. If you don't follow this naming convention for your accessors, you will not be able to take advantage of Cocoa's automatic support for AppleScriptability. There are several other areas where similar dependence on key-value coding requires you to follow these naming conventions.
Basically, key-value coding lets you write code that calls methods by giving the names of instance variables as strings. This enables you to write a single method which will call other methods based on the strings you provide, rather than having to make actual method calls (er, "to send actual messages") in a long case statement. Because of this, the actual method calls ("messages") can be determined at run time, not hard-coded at compile time. Furthermore, key-value coding gives the separate, added benefit of providing the data in the correct type without your having to code type coercions in a case statement."
Thanks, Bill! As you develop more confidence with Objective-C and Cocoa, spend some time digging through the key-value coding doc and examples. Here's a good link to start with:
OK, let's get back to this month's program...
Every time I sit down to tackle a new Mac programming environment or methodology, I always seem to find myself coming back to PictViewer. How am I going to get PictViewer up and running with this new setup. As soon as I had my first working version of Project Builder installed, the first thing I did was dig through the Cocoa doc, looking for the classes I'd need to master to create a resizable window, with scrollbars, I could usein which I could display an image. Once I figured that out, I'd then tackle some drag-and-drop classes so I could add that feature to the program.
Little did I know how easy (and cool) this would turn out to be.
Create the TinyViewer Project
Launch Project Builder and create a new project of type Cocoa Application. Name the app TinyViewer and save. In the Project Builder Files pane, click to open the triangle to the left of Resources, then open the triangle to the left of MainMenu.nib. This will reveal an item named English (assuming you are on an English-based Mac).
The .nib file is an Interface Builder file. Interface Builder is sort of like ResEdit on steroids. With it, you can customize all your favorite objects and encode them for later decoding when your program is actually run. The item named English in the Project Builder Files tab refers to the English-localized nib file. Figure 1 shows the Finder listing of my version of TinyViewer. Notice the directory named English.lproj and the file MainMenu.nib within that directory. That's the English version of the nib file, the one we'll be working with in this column.
Figure 1. The English.lproj folder inside the project folder.
Figure 2 shows a Terminal listing showing a localized application on my hard drive. I start by going into the /Applications directory, the doing a cd into the sub-directory Clock.app. If I looked at /Applications in a Finder window, Clock.app would just appear as a single application file. In reality, your packaged applications are a series of files, all rolled under a single directory, in this case named Clock.app. As Figure 2 shows, if you make your way down into /Applications/Clock.app/Contents/, you'll see a number of different files and directories, including a directory for each localized version of the app. You should definitely fire up Terminal and try this for yourself. Dive down into your favorite app, then look for English.lproj.
Figure 2. Follow the terminal commands to find your way to the localized .nib files
Editing the .nib File
Double-click on TinyViewer/Resources/MainMenu.nib/English in the project window Files tab. This will open your .nib file in Interface Builder. You'll likely see 4 Interface Builder windows appear. The window labeled Window (Figure 3) represents your app's main window. The window labeled MainMenu.nib - MainMenu (Figure 4) contains your app's menu bar. The window labeled MainMenu.nib (Figure 5) acts as a central repository for the resources/instances you'll be creating. And the window labeled Cocoa - Other (Figure 6) is a palette window.
Figure 3. The default TinyViewer window, shrunk for convenience.
Figure 4. The default application menubar.
Figure 5. The main .nib file navigation window.
Figure 6. The palettes window.
Note the row of icons at the top of the palette window (Figure 6). Clicking on one of the icons changes the set of items available from that section of the palette. Currently, there are 10 palette icons. In order, they are Menus, Views, Other, Windows, Data, Containers, GraphicsViews, AppleScript, MSFFormatterPalette, and Sherlock. Our focus will be on the third icon from the left, the Other palette. Click on the Other icon and your palette window should look like the one shown in Figure 6.
Click and drag an NSImageView out of the palette window into the window named Window. If you hover your cursor over an item in the palette window, a "tool tip" will appear that tells you the item type. Drag the NSImageView towards the upper-left corner of the Window window until a pair of crossed blue lines appear (see Figure 7).
Figure 7. Dragging an NSImageView onto your main window.
Next, click on the NSImageView icon to select it. 8 grow handles will appear. Drag the lower right grow handle to grow the NSImageView until the crossed blue lines appear as you approach the lower right corner of the window. The net result will be an NSImageView inset in the window about the thickness of a scrollbar on all four sides.
Now, let's bring up an inspector window and customize our NSImageView. Select Show Info from the Tools menu. The NSImageView Info window will appear (Figure 8). The Info window allows you to modify the currently selected object. In this case, we're inspecting our NSImageView object.
Figure 8. The Info window for our NSImageView.
Take a look at Figure 8. Your settings should look like this. Be sure the Editable checkbox is checked. This will enable "drag and drop". In fact, when you take the interface for a spin, try testing the interface with and without the Editable checkbox checked.
Next, select Size from the popup menu and compare your settings to those shown in Figure 9. Note that the Layout Rect fields will not necessarily match. Not to worry. It's just the difference between our window sizes. What's important is the Autosizing settings. To change those, click on the two lines in the inner square till each line turns into a pair of springs. Again, when you test the interface, play with these settings. Try it with one line and one spring, just to see what affect this has.
Figure 9. The NSImageView Info window, this time showing the Size settings.
Testing the Interface
OK, now let's take the interface for a spin. Select Test Interface from the File menu. Your window will appear, with an NSImageView area centered in the window. Click on a picture and drag it to the NSImageView field. The image should appear centered in the window. When you resize the window, the image should resize until it reaches its full size.
Play, play, play. Drag the image back out of the window and onto the desktop. A clipping file should appear. Double-click it and you can view your image directly in the Finder. Cool!
To exit the application, just select Quit from the File menu.
You should now be back in Interface Builder. Select Save from the File menu to save the .nib file. Now go back into Project Builder and run TinyViewer. Notice that TinyViewer appears in the dock as an icon, the main menu is titled "TinyViewer", your window appears, and is fully functional. Very cool!!
There's a terrific new Cocoa book out there you should definitely check out. It's called Cocoa Programming by Scott Anguish, Erik M. Buuck, and Donald A. Yacktman, published by Sams. You can find it at http://www.devdepot.com/books.html.
I can't say enough about Cocoa Programming. Chapter 1 has one of the clearest breakdowns of the Mac OS X development universe I've yet read. There's great coverage of Objective C, design patterns, memory management, strings, encoding/decoding, exhaustive coverage of the Cocoa frameworks, and just about anything else you might think of. And there, nestled in Chapter 3 you'll find the Cocoa Programming treatment of an NSImageView app. Great stuff. My highest recommendation.
Till Next Month...
Next month, we'll do more with Interface Builder, including exploring the details of the Info window and customizing the menu bar. See you then...
Dave Mark is a long-time Mac developer and author and has written a number of books on Macintosh development, including Learn C on the Macintosh, Learn C++ on the Macintosh, and The Macintosh Programming Primer series. Be sure to check out Dave's web site at http://www.spiderworks.com.