TweetFollow Us on Twitter

TinyViewer

Volume Number: 19 (2003)
Issue Number: 5
Column Tag: Programming

Getting Started

TinyViewer

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:

http://developer.apple.com/techpubs/macosx...

OK, let's get back to this month's program...

TinyViewer

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.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.