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

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 »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
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 below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more

Jobs Board

*Apple* Systems Administrator - JAMF - Syste...
Title: Apple Systems Administrator - JAMF ALTA is supporting a direct hire opportunity. This position is 100% Onsite for initial 3-6 months and then remote 1-2 Read more
Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.