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

The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »

Price Scanner via MacPrices.net

Sunday Sale: Apple Studio Display with Standa...
Amazon has the standard-glass Apple Studio Display on sale for $300 off MSRP for a limited time. Shipping is free: – Studio Display (Standard glass): $1299.97 $300 off MSRP For the latest prices and... Read more
Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more
Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more

Jobs Board

Licensed Practical Nurse - Womens Imaging *A...
Licensed Practical Nurse - Womens Imaging Apple Hill - PRN Location: York Hospital, York, PA Schedule: PRN/Per Diem Sign-On Bonus Eligible Remote/Hybrid Regular Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Operating Room Assistant - *Apple* Hill Sur...
Operating Room Assistant - Apple Hill Surgical Center - Day Location: WellSpan Health, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.